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.

sanitizer.go 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2017 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package markup
  6. import (
  7. "bytes"
  8. "io"
  9. "regexp"
  10. "sync"
  11. "code.gitea.io/gitea/modules/setting"
  12. "github.com/microcosm-cc/bluemonday"
  13. )
  14. // Sanitizer is a protection wrapper of *bluemonday.Policy which does not allow
  15. // any modification to the underlying policies once it's been created.
  16. type Sanitizer struct {
  17. policy *bluemonday.Policy
  18. init sync.Once
  19. }
  20. var sanitizer = &Sanitizer{}
  21. // NewSanitizer initializes sanitizer with allowed attributes based on settings.
  22. // Multiple calls to this function will only create one instance of Sanitizer during
  23. // entire application lifecycle.
  24. func NewSanitizer() {
  25. sanitizer.init.Do(func() {
  26. ReplaceSanitizer()
  27. })
  28. }
  29. // ReplaceSanitizer replaces the current sanitizer to account for changes in settings
  30. func ReplaceSanitizer() {
  31. sanitizer.policy = bluemonday.UGCPolicy()
  32. // For Chroma markdown plugin
  33. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(chroma )?language-[\w-]+$`)).OnElements("code")
  34. // Checkboxes
  35. sanitizer.policy.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  36. sanitizer.policy.AllowAttrs("checked", "disabled", "readonly").OnElements("input")
  37. // Custom URL-Schemes
  38. sanitizer.policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  39. // Allow keyword markup
  40. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^` + keywordClass + `$`)).OnElements("span")
  41. // Allow classes for anchors
  42. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`ref-issue`)).OnElements("a")
  43. // Allow classes for task lists
  44. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`task-list-item`)).OnElements("li")
  45. // Allow icons
  46. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^icon(\s+[\p{L}\p{N}_-]+)+$`)).OnElements("i")
  47. // Allow unlabelled labels
  48. sanitizer.policy.AllowNoAttrs().OnElements("label")
  49. // Allow classes for emojis
  50. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`emoji`)).OnElements("img")
  51. // Allow icons, checkboxes, emojis, and chroma syntax on span
  52. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(ui checkbox)|(ui checked checkbox)|(emoji))$|^([a-z][a-z0-9]{0,2})$`)).OnElements("span")
  53. // Allow generally safe attributes
  54. generalSafeAttrs := []string{"abbr", "accept", "accept-charset",
  55. "accesskey", "action", "align", "alt",
  56. "aria-describedby", "aria-hidden", "aria-label", "aria-labelledby",
  57. "axis", "border", "cellpadding", "cellspacing", "char",
  58. "charoff", "charset", "checked",
  59. "clear", "cols", "colspan", "color",
  60. "compact", "coords", "datetime", "dir",
  61. "disabled", "enctype", "for", "frame",
  62. "headers", "height", "hreflang",
  63. "hspace", "ismap", "label", "lang",
  64. "maxlength", "media", "method",
  65. "multiple", "name", "nohref", "noshade",
  66. "nowrap", "open", "prompt", "readonly", "rel", "rev",
  67. "rows", "rowspan", "rules", "scope",
  68. "selected", "shape", "size", "span",
  69. "start", "summary", "tabindex", "target",
  70. "title", "type", "usemap", "valign", "value",
  71. "vspace", "width", "itemprop",
  72. }
  73. generalSafeElements := []string{
  74. "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "br", "b", "i", "strong", "em", "a", "pre", "code", "img", "tt",
  75. "div", "ins", "del", "sup", "sub", "p", "ol", "ul", "table", "thead", "tbody", "tfoot", "blockquote",
  76. "dl", "dt", "dd", "kbd", "q", "samp", "var", "hr", "ruby", "rt", "rp", "li", "tr", "td", "th", "s", "strike", "summary",
  77. "details", "caption", "figure", "figcaption",
  78. "abbr", "bdo", "cite", "dfn", "mark", "small", "span", "time", "wbr",
  79. }
  80. sanitizer.policy.AllowAttrs(generalSafeAttrs...).OnElements(generalSafeElements...)
  81. sanitizer.policy.AllowAttrs("itemscope", "itemtype").OnElements("div")
  82. // FIXME: Need to handle longdesc in img but there is no easy way to do it
  83. // Custom keyword markup
  84. for _, rule := range setting.ExternalSanitizerRules {
  85. if rule.Regexp != nil {
  86. sanitizer.policy.AllowAttrs(rule.AllowAttr).Matching(rule.Regexp).OnElements(rule.Element)
  87. } else {
  88. sanitizer.policy.AllowAttrs(rule.AllowAttr).OnElements(rule.Element)
  89. }
  90. }
  91. }
  92. // Sanitize takes a string that contains a HTML fragment or document and applies policy whitelist.
  93. func Sanitize(s string) string {
  94. NewSanitizer()
  95. return sanitizer.policy.Sanitize(s)
  96. }
  97. // SanitizeReader sanitizes a Reader
  98. func SanitizeReader(r io.Reader) *bytes.Buffer {
  99. NewSanitizer()
  100. return sanitizer.policy.SanitizeReader(r)
  101. }
  102. // SanitizeBytes takes a []byte slice that contains a HTML fragment or document and applies policy whitelist.
  103. func SanitizeBytes(b []byte) []byte {
  104. if len(b) == 0 {
  105. // nothing to sanitize
  106. return b
  107. }
  108. NewSanitizer()
  109. return sanitizer.policy.SanitizeBytes(b)
  110. }