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 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2017 The Gogs Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package markup
  5. import (
  6. "io"
  7. "net/url"
  8. "regexp"
  9. "sync"
  10. "code.gitea.io/gitea/modules/setting"
  11. "github.com/microcosm-cc/bluemonday"
  12. )
  13. // Sanitizer is a protection wrapper of *bluemonday.Policy which does not allow
  14. // any modification to the underlying policies once it's been created.
  15. type Sanitizer struct {
  16. defaultPolicy *bluemonday.Policy
  17. rendererPolicies map[string]*bluemonday.Policy
  18. init sync.Once
  19. }
  20. var (
  21. sanitizer = &Sanitizer{}
  22. allowAllRegex = regexp.MustCompile(".+")
  23. )
  24. // NewSanitizer initializes sanitizer with allowed attributes based on settings.
  25. // Multiple calls to this function will only create one instance of Sanitizer during
  26. // entire application lifecycle.
  27. func NewSanitizer() {
  28. sanitizer.init.Do(func() {
  29. InitializeSanitizer()
  30. })
  31. }
  32. // InitializeSanitizer (re)initializes the current sanitizer to account for changes in settings
  33. func InitializeSanitizer() {
  34. sanitizer.rendererPolicies = map[string]*bluemonday.Policy{}
  35. sanitizer.defaultPolicy = createDefaultPolicy()
  36. for name, renderer := range renderers {
  37. sanitizerRules := renderer.SanitizerRules()
  38. if len(sanitizerRules) > 0 {
  39. policy := createDefaultPolicy()
  40. addSanitizerRules(policy, sanitizerRules)
  41. sanitizer.rendererPolicies[name] = policy
  42. }
  43. }
  44. }
  45. func createDefaultPolicy() *bluemonday.Policy {
  46. policy := bluemonday.UGCPolicy()
  47. // For JS code copy and Mermaid loading state
  48. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^code-block( is-loading)?$`)).OnElements("pre")
  49. // For color preview
  50. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^color-preview$`)).OnElements("span")
  51. // For attention
  52. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-\w+$`)).OnElements("strong")
  53. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-icon attention-\w+$`)).OnElements("span", "strong")
  54. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^svg octicon-\w+$`)).OnElements("svg")
  55. policy.AllowAttrs("viewBox", "width", "height", "aria-hidden").OnElements("svg")
  56. policy.AllowAttrs("fill-rule", "d").OnElements("path")
  57. // For Chroma markdown plugin
  58. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(chroma )?language-[\w-]+( display)?( is-loading)?$`)).OnElements("code")
  59. // Checkboxes
  60. policy.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  61. policy.AllowAttrs("checked", "disabled", "data-source-position").OnElements("input")
  62. // Custom URL-Schemes
  63. if len(setting.Markdown.CustomURLSchemes) > 0 {
  64. policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  65. } else {
  66. policy.AllowURLSchemesMatching(allowAllRegex)
  67. // Even if every scheme is allowed, these three are blocked for security reasons
  68. disallowScheme := func(*url.URL) bool {
  69. return false
  70. }
  71. policy.AllowURLSchemeWithCustomPolicy("javascript", disallowScheme)
  72. policy.AllowURLSchemeWithCustomPolicy("vbscript", disallowScheme)
  73. policy.AllowURLSchemeWithCustomPolicy("data", disallowScheme)
  74. }
  75. // Allow classes for anchors
  76. policy.AllowAttrs("class").Matching(regexp.MustCompile(`ref-issue( ref-external-issue)?`)).OnElements("a")
  77. // Allow classes for task lists
  78. policy.AllowAttrs("class").Matching(regexp.MustCompile(`task-list-item`)).OnElements("li")
  79. // Allow classes for org mode list item status.
  80. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(unchecked|checked|indeterminate)$`)).OnElements("li")
  81. // Allow icons
  82. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^icon(\s+[\p{L}\p{N}_-]+)+$`)).OnElements("i")
  83. // Allow unlabelled labels
  84. policy.AllowNoAttrs().OnElements("label")
  85. // Allow classes for emojis
  86. policy.AllowAttrs("class").Matching(regexp.MustCompile(`emoji`)).OnElements("img")
  87. // Allow icons, emojis, chroma syntax and keyword markup on span
  88. policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(emoji)|(language-math display)|(language-math inline))$|^([a-z][a-z0-9]{0,2})$|^` + keywordClass + `$`)).OnElements("span")
  89. // Allow 'style' attribute on text elements.
  90. policy.AllowAttrs("style").OnElements("span", "p")
  91. // Allow 'color' and 'background-color' properties for the style attribute on text elements.
  92. policy.AllowStyles("color", "background-color").OnElements("span", "p")
  93. // Allow generally safe attributes
  94. generalSafeAttrs := []string{
  95. "abbr", "accept", "accept-charset",
  96. "accesskey", "action", "align", "alt",
  97. "aria-describedby", "aria-hidden", "aria-label", "aria-labelledby",
  98. "axis", "border", "cellpadding", "cellspacing", "char",
  99. "charoff", "charset", "checked",
  100. "clear", "cols", "colspan", "color",
  101. "compact", "coords", "datetime", "dir",
  102. "disabled", "enctype", "for", "frame",
  103. "headers", "height", "hreflang",
  104. "hspace", "ismap", "label", "lang",
  105. "maxlength", "media", "method",
  106. "multiple", "name", "nohref", "noshade",
  107. "nowrap", "open", "prompt", "readonly", "rel", "rev",
  108. "rows", "rowspan", "rules", "scope",
  109. "selected", "shape", "size", "span",
  110. "start", "summary", "tabindex", "target",
  111. "title", "type", "usemap", "valign", "value",
  112. "vspace", "width", "itemprop",
  113. }
  114. generalSafeElements := []string{
  115. "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "br", "b", "i", "strong", "em", "a", "pre", "code", "img", "tt",
  116. "div", "ins", "del", "sup", "sub", "p", "ol", "ul", "table", "thead", "tbody", "tfoot", "blockquote",
  117. "dl", "dt", "dd", "kbd", "q", "samp", "var", "hr", "ruby", "rt", "rp", "li", "tr", "td", "th", "s", "strike", "summary",
  118. "details", "caption", "figure", "figcaption",
  119. "abbr", "bdo", "cite", "dfn", "mark", "small", "span", "time", "video", "wbr",
  120. }
  121. policy.AllowAttrs(generalSafeAttrs...).OnElements(generalSafeElements...)
  122. policy.AllowAttrs("src", "autoplay", "controls").OnElements("video")
  123. policy.AllowAttrs("itemscope", "itemtype").OnElements("div")
  124. // FIXME: Need to handle longdesc in img but there is no easy way to do it
  125. // Custom keyword markup
  126. addSanitizerRules(policy, setting.ExternalSanitizerRules)
  127. return policy
  128. }
  129. func addSanitizerRules(policy *bluemonday.Policy, rules []setting.MarkupSanitizerRule) {
  130. for _, rule := range rules {
  131. if rule.AllowDataURIImages {
  132. policy.AllowDataURIImages()
  133. }
  134. if rule.Element != "" {
  135. if rule.Regexp != nil {
  136. policy.AllowAttrs(rule.AllowAttr).Matching(rule.Regexp).OnElements(rule.Element)
  137. } else {
  138. policy.AllowAttrs(rule.AllowAttr).OnElements(rule.Element)
  139. }
  140. }
  141. }
  142. }
  143. // Sanitize takes a string that contains a HTML fragment or document and applies policy whitelist.
  144. func Sanitize(s string) string {
  145. NewSanitizer()
  146. return sanitizer.defaultPolicy.Sanitize(s)
  147. }
  148. // SanitizeReader sanitizes a Reader
  149. func SanitizeReader(r io.Reader, renderer string, w io.Writer) error {
  150. NewSanitizer()
  151. policy, exist := sanitizer.rendererPolicies[renderer]
  152. if !exist {
  153. policy = sanitizer.defaultPolicy
  154. }
  155. return policy.SanitizeReaderToWriter(r, w)
  156. }