Command line client for Write.as https://write.as/apps/cli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # bluemonday [![Build Status](https://travis-ci.org/microcosm-cc/bluemonday.svg?branch=master)](https://travis-ci.org/microcosm-cc/bluemonday) [![GoDoc](https://godoc.org/github.com/microcosm-cc/bluemonday?status.png)](https://godoc.org/github.com/microcosm-cc/bluemonday) [![Sourcegraph](https://sourcegraph.com/github.com/microcosm-cc/bluemonday/-/badge.svg)](https://sourcegraph.com/github.com/microcosm-cc/bluemonday?badge)
  2. bluemonday is a HTML sanitizer implemented in Go. It is fast and highly configurable.
  3. bluemonday takes untrusted user generated content as an input, and will return HTML that has been sanitised against a whitelist of approved HTML elements and attributes so that you can safely include the content in your web page.
  4. If you accept user generated content, and your server uses Go, you **need** bluemonday.
  5. The default policy for user generated content (`bluemonday.UGCPolicy().Sanitize()`) turns this:
  6. ```html
  7. Hello <STYLE>.XSS{background-image:url("javascript:alert('XSS')");}</STYLE><A CLASS=XSS></A>World
  8. ```
  9. Into a harmless:
  10. ```html
  11. Hello World
  12. ```
  13. And it turns this:
  14. ```html
  15. <a href="javascript:alert('XSS1')" onmouseover="alert('XSS2')">XSS<a>
  16. ```
  17. Into this:
  18. ```html
  19. XSS
  20. ```
  21. Whilst still allowing this:
  22. ```html
  23. <a href="http://www.google.com/">
  24. <img src="https://ssl.gstatic.com/accounts/ui/logo_2x.png"/>
  25. </a>
  26. ```
  27. To pass through mostly unaltered (it gained a rel="nofollow" which is a good thing for user generated content):
  28. ```html
  29. <a href="http://www.google.com/" rel="nofollow">
  30. <img src="https://ssl.gstatic.com/accounts/ui/logo_2x.png"/>
  31. </a>
  32. ```
  33. It protects sites from [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) attacks. There are many [vectors for an XSS attack](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet) and the best way to mitigate the risk is to sanitize user input against a known safe list of HTML elements and attributes.
  34. You should **always** run bluemonday **after** any other processing.
  35. If you use [blackfriday](https://github.com/russross/blackfriday) or [Pandoc](http://johnmacfarlane.net/pandoc/) then bluemonday should be run after these steps. This ensures that no insecure HTML is introduced later in your process.
  36. bluemonday is heavily inspired by both the [OWASP Java HTML Sanitizer](https://code.google.com/p/owasp-java-html-sanitizer/) and the [HTML Purifier](http://htmlpurifier.org/).
  37. ## Technical Summary
  38. Whitelist based, you need to either build a policy describing the HTML elements and attributes to permit (and the `regexp` patterns of attributes), or use one of the supplied policies representing good defaults.
  39. The policy containing the whitelist is applied using a fast non-validating, forward only, token-based parser implemented in the [Go net/html library](https://godoc.org/golang.org/x/net/html) by the core Go team.
  40. We expect to be supplied with well-formatted HTML (closing elements for every applicable open element, nested correctly) and so we do not focus on repairing badly nested or incomplete HTML. We focus on simply ensuring that whatever elements do exist are described in the policy whitelist and that attributes and links are safe for use on your web page. [GIGO](http://en.wikipedia.org/wiki/Garbage_in,_garbage_out) does apply and if you feed it bad HTML bluemonday is not tasked with figuring out how to make it good again.
  41. ### Supported Go Versions
  42. bluemonday is tested against Go 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, and tip.
  43. We do not support Go 1.0 as we depend on `golang.org/x/net/html` which includes a reference to `io.ErrNoProgress` which did not exist in Go 1.0.
  44. ## Is it production ready?
  45. *Yes*
  46. We are using bluemonday in production having migrated from the widely used and heavily field tested OWASP Java HTML Sanitizer.
  47. We are passing our extensive test suite (including AntiSamy tests as well as tests for any issues raised). Check for any [unresolved issues](https://github.com/microcosm-cc/bluemonday/issues?page=1&state=open) to see whether anything may be a blocker for you.
  48. We invite pull requests and issues to help us ensure we are offering comprehensive protection against various attacks via user generated content.
  49. ## Usage
  50. Install in your `${GOPATH}` using `go get -u github.com/microcosm-cc/bluemonday`
  51. Then call it:
  52. ```go
  53. package main
  54. import (
  55. "fmt"
  56. "github.com/microcosm-cc/bluemonday"
  57. )
  58. func main() {
  59. // Do this once for each unique policy, and use the policy for the life of the program
  60. // Policy creation/editing is not safe to use in multiple goroutines
  61. p := bluemonday.UGCPolicy()
  62. // The policy can then be used to sanitize lots of input and it is safe to use the policy in multiple goroutines
  63. html := p.Sanitize(
  64. `<a onblur="alert(secret)" href="http://www.google.com">Google</a>`,
  65. )
  66. // Output:
  67. // <a href="http://www.google.com" rel="nofollow">Google</a>
  68. fmt.Println(html)
  69. }
  70. ```
  71. We offer three ways to call Sanitize:
  72. ```go
  73. p.Sanitize(string) string
  74. p.SanitizeBytes([]byte) []byte
  75. p.SanitizeReader(io.Reader) bytes.Buffer
  76. ```
  77. If you are obsessed about performance, `p.SanitizeReader(r).Bytes()` will return a `[]byte` without performing any unnecessary casting of the inputs or outputs. Though the difference is so negligible you should never need to care.
  78. You can build your own policies:
  79. ```go
  80. package main
  81. import (
  82. "fmt"
  83. "github.com/microcosm-cc/bluemonday"
  84. )
  85. func main() {
  86. p := bluemonday.NewPolicy()
  87. // Require URLs to be parseable by net/url.Parse and either:
  88. // mailto: http:// or https://
  89. p.AllowStandardURLs()
  90. // We only allow <p> and <a href="">
  91. p.AllowAttrs("href").OnElements("a")
  92. p.AllowElements("p")
  93. html := p.Sanitize(
  94. `<a onblur="alert(secret)" href="http://www.google.com">Google</a>`,
  95. )
  96. // Output:
  97. // <a href="http://www.google.com">Google</a>
  98. fmt.Println(html)
  99. }
  100. ```
  101. We ship two default policies:
  102. 1. `bluemonday.StrictPolicy()` which can be thought of as equivalent to stripping all HTML elements and their attributes as it has nothing on its whitelist. 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.
  103. 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* whitelist 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.
  104. ## Policy Building
  105. 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:
  106. 1. Avoid anything other than the standard HTML elements
  107. 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
  108. 1. Avoid anything other than plain HTML attributes with values matched to a regexp
  109. 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()`.
  110. To create a new policy:
  111. ```go
  112. p := bluemonday.NewPolicy()
  113. ```
  114. To add elements to a policy either add just the elements:
  115. ```go
  116. p.AllowElements("b", "strong")
  117. ```
  118. Or add elements as a virtue of adding an attribute:
  119. ```go
  120. // Not the recommended pattern, see the recommendation on using .Matching() below
  121. p.AllowAttrs("nowrap").OnElements("td", "th")
  122. ```
  123. Attributes can either be added to all elements:
  124. ```go
  125. p.AllowAttrs("dir").Matching(regexp.MustCompile("(?i)rtl|ltr")).Globally()
  126. ```
  127. Or attributes can be added to specific elements:
  128. ```go
  129. // Not the recommended pattern, see the recommendation on using .Matching() below
  130. p.AllowAttrs("value").OnElements("li")
  131. ```
  132. It is **always** recommended that an attribute be made to match a pattern. XSS in HTML attributes is very easy otherwise:
  133. ```go
  134. // \p{L} matches unicode letters, \p{N} matches unicode numbers
  135. p.AllowAttrs("title").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).Globally()
  136. ```
  137. You can stop at any time and call .Sanitize():
  138. ```go
  139. // string htmlIn passed in from a HTTP POST
  140. htmlOut := p.Sanitize(htmlIn)
  141. ```
  142. And you can take any existing policy and extend it:
  143. ```go
  144. p := bluemonday.UGCPolicy()
  145. p.AllowElements("fieldset", "select", "option")
  146. ```
  147. ### Links
  148. Links are difficult beasts to sanitise safely and also one of the biggest attack vectors for malicious content.
  149. It is possible to do this:
  150. ```go
  151. p.AllowAttrs("href").Matching(regexp.MustCompile(`(?i)mailto|https?`)).OnElements("a")
  152. ```
  153. But that will not protect you as the regular expression is insufficient in this case to have prevented a malformed value doing something unexpected.
  154. We provide some additional global options for safely working with links.
  155. `RequireParseableURLs` will ensure that URLs are parseable by Go's `net/url` package:
  156. ```go
  157. p.RequireParseableURLs(true)
  158. ```
  159. If you have enabled parseable URLs then the following option will `AllowRelativeURLs`. By default this is disabled (bluemonday is a whitelist 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):
  160. ```go
  161. p.AllowRelativeURLs(true)
  162. ```
  163. If you have enabled parseable URLs then you can whitelist 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 will allow for a blank scheme:
  164. ```go
  165. p.AllowURLSchemes("mailto", "http", "https")
  166. ```
  167. Regardless of whether you have enabled parseable URLs, you can force all URLs to have a rel="nofollow" attribute. This will be added if it does not exist, but only when the `href` is valid:
  168. ```go
  169. // This applies to "a" "area" "link" elements that have a "href" attribute
  170. p.RequireNoFollowOnLinks(true)
  171. ```
  172. We provide a convenience method that applies all of the above, but you will still need to whitelist the linkable elements for the URL rules to be applied to:
  173. ```go
  174. p.AllowStandardURLs()
  175. p.AllowAttrs("cite").OnElements("blockquote", "q")
  176. p.AllowAttrs("href").OnElements("a", "area")
  177. p.AllowAttrs("src").OnElements("img")
  178. ```
  179. An additional complexity regarding links is the data URI as defined in [RFC2397](http://tools.ietf.org/html/rfc2397). The data URI allows for images to be served inline using this format:
  180. ```html
  181. <img src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=">
  182. ```
  183. We have provided a helper to verify the mimetype followed by base64 content of data URIs links:
  184. ```go
  185. p.AllowDataURIImages()
  186. ```
  187. That helper will enable GIF, JPEG, PNG and WEBP images.
  188. It should be noted that there is a potential [security](http://palizine.plynt.com/issues/2010Oct/bypass-xss-filters/) [risk](https://capec.mitre.org/data/definitions/244.html) with the use of data URI links. You should only enable data URI links if you already trust the content.
  189. We also have some features to help deal with user generated content:
  190. ```go
  191. p.AddTargetBlankToFullyQualifiedLinks(true)
  192. ```
  193. This will ensure that anchor `<a href="" />` links that are fully qualified (the href destination includes a host name) will get `target="_blank"` added to them.
  194. Additionally any link that has `target="_blank"` after the policy has been applied will also have the `rel` attribute adjusted to add `noopener`. This means a link may start like `<a href="//host/path"/>` and will end up as `<a href="//host/path" rel="noopener" target="_blank">`. It is important to note that the addition of `noopener` is a security feature and not an issue. There is an unfortunate feature to browsers that a browser window opened as a result of `target="_blank"` can still control the opener (your web page) and this protects against that. The background to this can be found here: [https://dev.to/ben/the-targetblank-vulnerability-by-example](https://dev.to/ben/the-targetblank-vulnerability-by-example)
  195. ### Policy Building Helpers
  196. We also bundle some helpers to simplify policy building:
  197. ```go
  198. // Permits the "dir", "id", "lang", "title" attributes globally
  199. p.AllowStandardAttributes()
  200. // Permits the "img" element and its standard attributes
  201. p.AllowImages()
  202. // Permits ordered and unordered lists, and also definition lists
  203. p.AllowLists()
  204. // Permits HTML tables and all applicable elements and non-styling attributes
  205. p.AllowTables()
  206. ```
  207. ### Invalid Instructions
  208. The following are invalid:
  209. ```go
  210. // This does not say where the attributes are allowed, you need to add
  211. // .Globally() or .OnElements(...)
  212. // This will be ignored without error.
  213. p.AllowAttrs("value")
  214. // This does not say where the attributes are allowed, you need to add
  215. // .Globally() or .OnElements(...)
  216. // This will be ignored without error.
  217. p.AllowAttrs(
  218. "type",
  219. ).Matching(
  220. regexp.MustCompile("(?i)^(circle|disc|square|a|A|i|I|1)$"),
  221. )
  222. ```
  223. Both examples exhibit the same issue, they declare attributes but do not then specify whether they are whitelisted globally or only on specific elements (and which elements). Attributes belong to one or more elements, and the policy needs to declare this.
  224. ## Limitations
  225. We are not yet including any tools to help whitelist and sanitize CSS. Which means that unless you wish to do the heavy lifting in a single regular expression (inadvisable), **you should not allow the "style" attribute anywhere**.
  226. It is not the job of bluemonday to fix your bad HTML, it is merely the job of bluemonday to prevent malicious HTML getting through. If you have mismatched HTML elements, or non-conforming nesting of elements, those will remain. But if you have well-structured HTML bluemonday will not break it.
  227. ## TODO
  228. * Add support for CSS sanitisation to allow some CSS properties based on a whitelist, possibly using the [Gorilla CSS3 scanner](http://www.gorillatoolkit.org/pkg/css/scanner) - PRs welcome so long as testing covers XSS and demonstrates safety first
  229. * Investigate whether devs want to blacklist elements and attributes. This would allow devs to take an existing policy (such as the `bluemonday.UGCPolicy()` ) that encapsulates 90% of what they're looking for but does more than they need, and to remove the extra things they do not want to make it 100% what they want
  230. * Investigate whether devs want a validating HTML mode, in which the HTML elements are not just transformed into a balanced tree (every start tag has a closing tag at the correct depth) but also that elements and character data appear only in their allowed context (i.e. that a `table` element isn't a descendent of a `caption`, that `colgroup`, `thead`, `tbody`, `tfoot` and `tr` are permitted, and that character data is not permitted)
  231. ## Development
  232. If you have cloned this repo you will probably need the dependency:
  233. `go get golang.org/x/net/html`
  234. Gophers can use their familiar tools:
  235. `go build`
  236. `go test`
  237. I personally use a Makefile as it spares typing the same args over and over whilst providing consistency for those of us who jump from language to language and enjoy just typing `make` in a project directory and watch magic happen.
  238. `make` will build, vet, test and install the library.
  239. `make clean` will remove the library from a *single* `${GOPATH}/pkg` directory tree
  240. `make test` will run the tests
  241. `make cover` will run the tests and *open a browser window* with the coverage report
  242. `make lint` will run golint (install via `go get github.com/golang/lint/golint`)
  243. ## Long term goals
  244. 1. Open the code to adversarial peer review similar to the [Attack Review Ground Rules](https://code.google.com/p/owasp-java-html-sanitizer/wiki/AttackReviewGroundRules)
  245. 1. Raise funds and pay for an external security review