sanitizer.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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(`http[s]?://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. if tagName == "a" {
  112. return []string{"rel", "target", "referrerpolicy"}, []string{`rel="noopener noreferrer"`, `target="_blank"`, `referrerpolicy="no-referrer"`}
  113. }
  114. if tagName == "video" || tagName == "audio" {
  115. return []string{"controls"}, []string{"controls"}
  116. }
  117. return nil, nil
  118. }
  119. func isValidTag(tagName string) bool {
  120. for element := range getTagWhitelist() {
  121. if tagName == element {
  122. return true
  123. }
  124. }
  125. return false
  126. }
  127. func isValidAttribute(tagName, attributeName string) bool {
  128. for element, attributes := range getTagWhitelist() {
  129. if tagName == element {
  130. if inList(attributeName, attributes) {
  131. return true
  132. }
  133. }
  134. }
  135. return false
  136. }
  137. func isExternalResourceAttribute(attribute string) bool {
  138. switch attribute {
  139. case "src", "href", "poster", "cite":
  140. return true
  141. default:
  142. return false
  143. }
  144. }
  145. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  146. if tagName == "img" {
  147. hasHeight := false
  148. hasWidth := false
  149. for _, attribute := range attributes {
  150. if attribute.Key == "height" && attribute.Val == "1" {
  151. hasHeight = true
  152. }
  153. if attribute.Key == "width" && attribute.Val == "1" {
  154. hasWidth = true
  155. }
  156. }
  157. return hasHeight && hasWidth
  158. }
  159. return false
  160. }
  161. func hasRequiredAttributes(tagName string, attributes []string) bool {
  162. elements := make(map[string][]string)
  163. elements["a"] = []string{"href"}
  164. elements["iframe"] = []string{"src"}
  165. elements["img"] = []string{"src"}
  166. elements["source"] = []string{"src"}
  167. for element, attrs := range elements {
  168. if tagName == element {
  169. for _, attribute := range attributes {
  170. for _, attr := range attrs {
  171. if attr == attribute {
  172. return true
  173. }
  174. }
  175. }
  176. return false
  177. }
  178. }
  179. return true
  180. }
  181. func hasValidScheme(src string) bool {
  182. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  183. whitelist := []string{
  184. "apt://",
  185. "bitcoin://",
  186. "callto://",
  187. "ed2k://",
  188. "facetime://",
  189. "feed://",
  190. "ftp://",
  191. "geo://",
  192. "gopher://",
  193. "git://",
  194. "http://",
  195. "https://",
  196. "irc://",
  197. "irc6://",
  198. "ircs://",
  199. "itms://",
  200. "jabber://",
  201. "magnet://",
  202. "mailto://",
  203. "maps://",
  204. "news://",
  205. "nfs://",
  206. "nntp://",
  207. "rtmp://",
  208. "sip://",
  209. "sips://",
  210. "skype://",
  211. "smb://",
  212. "sms://",
  213. "spotify://",
  214. "ssh://",
  215. "sftp://",
  216. "steam://",
  217. "svn://",
  218. "tel://",
  219. "webcal://",
  220. "xmpp://",
  221. }
  222. for _, prefix := range whitelist {
  223. if strings.HasPrefix(src, prefix) {
  224. return true
  225. }
  226. }
  227. return false
  228. }
  229. func isBlacklistedResource(src string) bool {
  230. blacklist := []string{
  231. "feedsportal.com",
  232. "api.flattr.com",
  233. "stats.wordpress.com",
  234. "plus.google.com/share",
  235. "twitter.com/share",
  236. "feeds.feedburner.com",
  237. }
  238. for _, element := range blacklist {
  239. if strings.Contains(src, element) {
  240. return true
  241. }
  242. }
  243. return false
  244. }
  245. func isValidIframeSource(src string) bool {
  246. whitelist := []string{
  247. "http://www.youtube.com",
  248. "https://www.youtube.com",
  249. "https://www.youtube-nocookie.com",
  250. "http://player.vimeo.com",
  251. "https://player.vimeo.com",
  252. "http://www.dailymotion.com",
  253. "https://www.dailymotion.com",
  254. "http://vk.com",
  255. "https://vk.com",
  256. "http://soundcloud.com",
  257. "https://soundcloud.com",
  258. "http://w.soundcloud.com",
  259. "https://w.soundcloud.com",
  260. "http://bandcamp.com",
  261. "https://bandcamp.com",
  262. }
  263. for _, prefix := range whitelist {
  264. if strings.HasPrefix(src, prefix) {
  265. return true
  266. }
  267. }
  268. return false
  269. }
  270. func getTagWhitelist() map[string][]string {
  271. whitelist := make(map[string][]string)
  272. whitelist["img"] = []string{"alt", "title", "src"}
  273. whitelist["audio"] = []string{"src"}
  274. whitelist["video"] = []string{"poster", "height", "width", "src"}
  275. whitelist["source"] = []string{"src", "type"}
  276. whitelist["dt"] = []string{}
  277. whitelist["dd"] = []string{}
  278. whitelist["dl"] = []string{}
  279. whitelist["table"] = []string{}
  280. whitelist["caption"] = []string{}
  281. whitelist["thead"] = []string{}
  282. whitelist["tfooter"] = []string{}
  283. whitelist["tr"] = []string{}
  284. whitelist["td"] = []string{"rowspan", "colspan"}
  285. whitelist["th"] = []string{"rowspan", "colspan"}
  286. whitelist["h1"] = []string{}
  287. whitelist["h2"] = []string{}
  288. whitelist["h3"] = []string{}
  289. whitelist["h4"] = []string{}
  290. whitelist["h5"] = []string{}
  291. whitelist["h6"] = []string{}
  292. whitelist["strong"] = []string{}
  293. whitelist["em"] = []string{}
  294. whitelist["code"] = []string{}
  295. whitelist["pre"] = []string{}
  296. whitelist["blockquote"] = []string{}
  297. whitelist["q"] = []string{"cite"}
  298. whitelist["p"] = []string{}
  299. whitelist["ul"] = []string{}
  300. whitelist["li"] = []string{}
  301. whitelist["ol"] = []string{}
  302. whitelist["br"] = []string{}
  303. whitelist["del"] = []string{}
  304. whitelist["a"] = []string{"href", "title"}
  305. whitelist["figure"] = []string{}
  306. whitelist["figcaption"] = []string{}
  307. whitelist["cite"] = []string{}
  308. whitelist["time"] = []string{"datetime"}
  309. whitelist["abbr"] = []string{"title"}
  310. whitelist["acronym"] = []string{"title"}
  311. whitelist["wbr"] = []string{}
  312. whitelist["dfn"] = []string{}
  313. whitelist["sub"] = []string{}
  314. whitelist["sup"] = []string{}
  315. whitelist["var"] = []string{}
  316. whitelist["samp"] = []string{}
  317. whitelist["s"] = []string{}
  318. whitelist["del"] = []string{}
  319. whitelist["ins"] = []string{}
  320. whitelist["kbd"] = []string{}
  321. whitelist["rp"] = []string{}
  322. whitelist["rt"] = []string{}
  323. whitelist["rtc"] = []string{}
  324. whitelist["ruby"] = []string{}
  325. whitelist["iframe"] = []string{"width", "height", "frameborder", "src", "allowfullscreen"}
  326. return whitelist
  327. }
  328. func inList(needle string, haystack []string) bool {
  329. for _, element := range haystack {
  330. if element == needle {
  331. return true
  332. }
  333. }
  334. return false
  335. }
  336. func rewriteIframeURL(link string) string {
  337. matches := youtubeEmbedRegex.FindStringSubmatch(link)
  338. if len(matches) == 2 {
  339. return `https://www.youtube-nocookie.com/embed/` + matches[1]
  340. }
  341. return link
  342. }
  343. // Blacklisted tags remove the tag and all descendants.
  344. func isBlacklistedTag(tagName string) bool {
  345. blacklist := []string{
  346. "noscript",
  347. "script",
  348. "style",
  349. }
  350. for _, element := range blacklist {
  351. if element == tagName {
  352. return true
  353. }
  354. }
  355. return false
  356. }