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

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