sanitizer.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package sanitizer
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "regexp"
  10. "strings"
  11. "github.com/miniflux/miniflux/url"
  12. "golang.org/x/net/html"
  13. )
  14. var (
  15. youtubeEmbedRegex = regexp.MustCompile(`//www\.youtube\.com/embed/(.*)`)
  16. )
  17. // Sanitize returns safe HTML.
  18. func Sanitize(baseURL, input string) string {
  19. tokenizer := html.NewTokenizer(bytes.NewBufferString(input))
  20. var buffer bytes.Buffer
  21. var tagStack []string
  22. blacklistedTagDepth := 0
  23. for {
  24. if tokenizer.Next() == html.ErrorToken {
  25. err := tokenizer.Err()
  26. if err == io.EOF {
  27. return buffer.String()
  28. }
  29. return ""
  30. }
  31. token := tokenizer.Token()
  32. switch token.Type {
  33. case html.TextToken:
  34. if blacklistedTagDepth > 0 {
  35. continue
  36. }
  37. buffer.WriteString(html.EscapeString(token.Data))
  38. case html.StartTagToken:
  39. tagName := token.DataAtom.String()
  40. if !isPixelTracker(tagName, token.Attr) && isValidTag(tagName) {
  41. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr)
  42. if hasRequiredAttributes(tagName, attrNames) {
  43. if len(attrNames) > 0 {
  44. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  45. } else {
  46. buffer.WriteString("<" + tagName + ">")
  47. }
  48. tagStack = append(tagStack, tagName)
  49. }
  50. } else if isBlacklistedTag(tagName) {
  51. blacklistedTagDepth++
  52. }
  53. case html.EndTagToken:
  54. tagName := token.DataAtom.String()
  55. if isValidTag(tagName) && inList(tagName, tagStack) {
  56. buffer.WriteString(fmt.Sprintf("</%s>", tagName))
  57. } else if isBlacklistedTag(tagName) {
  58. blacklistedTagDepth--
  59. }
  60. case html.SelfClosingTagToken:
  61. tagName := token.DataAtom.String()
  62. if !isPixelTracker(tagName, token.Attr) && isValidTag(tagName) {
  63. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr)
  64. if hasRequiredAttributes(tagName, attrNames) {
  65. if len(attrNames) > 0 {
  66. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  67. } else {
  68. buffer.WriteString("<" + tagName + "/>")
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }
  75. func sanitizeAttributes(baseURL, tagName string, attributes []html.Attribute) ([]string, string) {
  76. var htmlAttrs, attrNames []string
  77. var err error
  78. for _, attribute := range attributes {
  79. value := attribute.Val
  80. if !isValidAttribute(tagName, attribute.Key) {
  81. continue
  82. }
  83. if isExternalResourceAttribute(attribute.Key) {
  84. if tagName == "iframe" {
  85. if isValidIframeSource(attribute.Val) {
  86. value = rewriteIframeURL(attribute.Val)
  87. } else {
  88. continue
  89. }
  90. } else {
  91. value, err = url.AbsoluteURL(baseURL, value)
  92. if err != nil {
  93. continue
  94. }
  95. if !hasValidScheme(value) || isBlacklistedResource(value) {
  96. continue
  97. }
  98. }
  99. }
  100. attrNames = append(attrNames, attribute.Key)
  101. htmlAttrs = append(htmlAttrs, fmt.Sprintf(`%s="%s"`, attribute.Key, html.EscapeString(value)))
  102. }
  103. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName)
  104. if len(extraAttrNames) > 0 {
  105. attrNames = append(attrNames, extraAttrNames...)
  106. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  107. }
  108. return attrNames, strings.Join(htmlAttrs, " ")
  109. }
  110. func getExtraAttributes(tagName string) ([]string, []string) {
  111. switch tagName {
  112. case "a":
  113. return []string{"rel", "target", "referrerpolicy"}, []string{`rel="noopener noreferrer"`, `target="_blank"`, `referrerpolicy="no-referrer"`}
  114. case "video", "audio":
  115. return []string{"controls"}, []string{"controls"}
  116. case "iframe":
  117. return []string{"sandbox"}, []string{`sandbox="allow-scripts allow-same-origin"`}
  118. default:
  119. return nil, nil
  120. }
  121. }
  122. func isValidTag(tagName string) bool {
  123. for element := range getTagWhitelist() {
  124. if tagName == element {
  125. return true
  126. }
  127. }
  128. return false
  129. }
  130. func isValidAttribute(tagName, attributeName string) bool {
  131. for element, attributes := range getTagWhitelist() {
  132. if tagName == element {
  133. if inList(attributeName, attributes) {
  134. return true
  135. }
  136. }
  137. }
  138. return false
  139. }
  140. func isExternalResourceAttribute(attribute string) bool {
  141. switch attribute {
  142. case "src", "href", "poster", "cite":
  143. return true
  144. default:
  145. return false
  146. }
  147. }
  148. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  149. if tagName == "img" {
  150. hasHeight := false
  151. hasWidth := false
  152. for _, attribute := range attributes {
  153. if attribute.Key == "height" && attribute.Val == "1" {
  154. hasHeight = true
  155. }
  156. if attribute.Key == "width" && attribute.Val == "1" {
  157. hasWidth = true
  158. }
  159. }
  160. return hasHeight && hasWidth
  161. }
  162. return false
  163. }
  164. func hasRequiredAttributes(tagName string, attributes []string) bool {
  165. elements := make(map[string][]string)
  166. elements["a"] = []string{"href"}
  167. elements["iframe"] = []string{"src"}
  168. elements["img"] = []string{"src"}
  169. elements["source"] = []string{"src"}
  170. for element, attrs := range elements {
  171. if tagName == element {
  172. for _, attribute := range attributes {
  173. for _, attr := range attrs {
  174. if attr == attribute {
  175. return true
  176. }
  177. }
  178. }
  179. return false
  180. }
  181. }
  182. return true
  183. }
  184. func hasValidScheme(src string) bool {
  185. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  186. whitelist := []string{
  187. "apt://",
  188. "bitcoin://",
  189. "callto://",
  190. "ed2k://",
  191. "facetime://",
  192. "feed://",
  193. "ftp://",
  194. "geo://",
  195. "gopher://",
  196. "git://",
  197. "http://",
  198. "https://",
  199. "irc://",
  200. "irc6://",
  201. "ircs://",
  202. "itms://",
  203. "jabber://",
  204. "magnet://",
  205. "mailto://",
  206. "maps://",
  207. "news://",
  208. "nfs://",
  209. "nntp://",
  210. "rtmp://",
  211. "sip://",
  212. "sips://",
  213. "skype://",
  214. "smb://",
  215. "sms://",
  216. "spotify://",
  217. "ssh://",
  218. "sftp://",
  219. "steam://",
  220. "svn://",
  221. "tel://",
  222. "webcal://",
  223. "xmpp://",
  224. }
  225. for _, prefix := range whitelist {
  226. if strings.HasPrefix(src, prefix) {
  227. return true
  228. }
  229. }
  230. return false
  231. }
  232. func isBlacklistedResource(src string) bool {
  233. blacklist := []string{
  234. "feedsportal.com",
  235. "api.flattr.com",
  236. "stats.wordpress.com",
  237. "plus.google.com/share",
  238. "twitter.com/share",
  239. "feeds.feedburner.com",
  240. }
  241. for _, element := range blacklist {
  242. if strings.Contains(src, element) {
  243. return true
  244. }
  245. }
  246. return false
  247. }
  248. func isValidIframeSource(src string) bool {
  249. whitelist := []string{
  250. "//www.youtube.com",
  251. "http://www.youtube.com",
  252. "https://www.youtube.com",
  253. "https://www.youtube-nocookie.com",
  254. "http://player.vimeo.com",
  255. "https://player.vimeo.com",
  256. "http://www.dailymotion.com",
  257. "https://www.dailymotion.com",
  258. "http://vk.com",
  259. "https://vk.com",
  260. "http://soundcloud.com",
  261. "https://soundcloud.com",
  262. "http://w.soundcloud.com",
  263. "https://w.soundcloud.com",
  264. "http://bandcamp.com",
  265. "https://bandcamp.com",
  266. "https://cdn.embedly.com",
  267. }
  268. for _, prefix := range whitelist {
  269. if strings.HasPrefix(src, prefix) {
  270. return true
  271. }
  272. }
  273. return false
  274. }
  275. func getTagWhitelist() map[string][]string {
  276. whitelist := make(map[string][]string)
  277. whitelist["img"] = []string{"alt", "title", "src"}
  278. whitelist["audio"] = []string{"src"}
  279. whitelist["video"] = []string{"poster", "height", "width", "src"}
  280. whitelist["source"] = []string{"src", "type"}
  281. whitelist["dt"] = []string{}
  282. whitelist["dd"] = []string{}
  283. whitelist["dl"] = []string{}
  284. whitelist["table"] = []string{}
  285. whitelist["caption"] = []string{}
  286. whitelist["thead"] = []string{}
  287. whitelist["tfooter"] = []string{}
  288. whitelist["tr"] = []string{}
  289. whitelist["td"] = []string{"rowspan", "colspan"}
  290. whitelist["th"] = []string{"rowspan", "colspan"}
  291. whitelist["h1"] = []string{}
  292. whitelist["h2"] = []string{}
  293. whitelist["h3"] = []string{}
  294. whitelist["h4"] = []string{}
  295. whitelist["h5"] = []string{}
  296. whitelist["h6"] = []string{}
  297. whitelist["strong"] = []string{}
  298. whitelist["em"] = []string{}
  299. whitelist["code"] = []string{}
  300. whitelist["pre"] = []string{}
  301. whitelist["blockquote"] = []string{}
  302. whitelist["q"] = []string{"cite"}
  303. whitelist["p"] = []string{}
  304. whitelist["ul"] = []string{}
  305. whitelist["li"] = []string{}
  306. whitelist["ol"] = []string{}
  307. whitelist["br"] = []string{}
  308. whitelist["del"] = []string{}
  309. whitelist["a"] = []string{"href", "title"}
  310. whitelist["figure"] = []string{}
  311. whitelist["figcaption"] = []string{}
  312. whitelist["cite"] = []string{}
  313. whitelist["time"] = []string{"datetime"}
  314. whitelist["abbr"] = []string{"title"}
  315. whitelist["acronym"] = []string{"title"}
  316. whitelist["wbr"] = []string{}
  317. whitelist["dfn"] = []string{}
  318. whitelist["sub"] = []string{}
  319. whitelist["sup"] = []string{}
  320. whitelist["var"] = []string{}
  321. whitelist["samp"] = []string{}
  322. whitelist["s"] = []string{}
  323. whitelist["del"] = []string{}
  324. whitelist["ins"] = []string{}
  325. whitelist["kbd"] = []string{}
  326. whitelist["rp"] = []string{}
  327. whitelist["rt"] = []string{}
  328. whitelist["rtc"] = []string{}
  329. whitelist["ruby"] = []string{}
  330. whitelist["iframe"] = []string{"width", "height", "frameborder", "src", "allowfullscreen"}
  331. return whitelist
  332. }
  333. func inList(needle string, haystack []string) bool {
  334. for _, element := range haystack {
  335. if element == needle {
  336. return true
  337. }
  338. }
  339. return false
  340. }
  341. func rewriteIframeURL(link string) string {
  342. matches := youtubeEmbedRegex.FindStringSubmatch(link)
  343. if len(matches) == 2 {
  344. return `https://www.youtube-nocookie.com/embed/` + matches[1]
  345. }
  346. return link
  347. }
  348. // Blacklisted tags remove the tag and all descendants.
  349. func isBlacklistedTag(tagName string) bool {
  350. blacklist := []string{
  351. "noscript",
  352. "script",
  353. "style",
  354. }
  355. for _, element := range blacklist {
  356. if element == tagName {
  357. return true
  358. }
  359. }
  360. return false
  361. }