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.

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