sanitizer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sanitizer // import "miniflux.app/v2/internal/reader/sanitizer"
  4. import (
  5. "io"
  6. "net/url"
  7. "slices"
  8. "strconv"
  9. "strings"
  10. "miniflux.app/v2/internal/config"
  11. "miniflux.app/v2/internal/reader/urlcleaner"
  12. "miniflux.app/v2/internal/urllib"
  13. "golang.org/x/net/html"
  14. )
  15. var (
  16. tagAllowList = map[string][]string{
  17. "a": {"href", "title", "id"},
  18. "abbr": {"title"},
  19. "acronym": {"title"},
  20. "aside": {},
  21. "audio": {"src"},
  22. "blockquote": {},
  23. "b": {},
  24. "br": {},
  25. "caption": {},
  26. "cite": {},
  27. "code": {},
  28. "dd": {"id"},
  29. "del": {},
  30. "dfn": {},
  31. "dl": {"id"},
  32. "dt": {"id"},
  33. "em": {},
  34. "figcaption": {},
  35. "figure": {},
  36. "h1": {"id"},
  37. "h2": {"id"},
  38. "h3": {"id"},
  39. "h4": {"id"},
  40. "h5": {"id"},
  41. "h6": {"id"},
  42. "hr": {},
  43. "iframe": {"width", "height", "frameborder", "src", "allowfullscreen"},
  44. "img": {"alt", "title", "src", "srcset", "sizes", "width", "height"},
  45. "ins": {},
  46. "kbd": {},
  47. "li": {"id"},
  48. "ol": {"id"},
  49. "p": {},
  50. "picture": {},
  51. "pre": {},
  52. "q": {"cite"},
  53. "rp": {},
  54. "rt": {},
  55. "rtc": {},
  56. "ruby": {},
  57. "s": {},
  58. "samp": {},
  59. "source": {"src", "type", "srcset", "sizes", "media"},
  60. "strong": {},
  61. "sub": {},
  62. "sup": {"id"},
  63. "table": {},
  64. "td": {"rowspan", "colspan"},
  65. "tfoot": {},
  66. "th": {"rowspan", "colspan"},
  67. "thead": {},
  68. "time": {"datetime"},
  69. "tr": {},
  70. "u": {},
  71. "ul": {"id"},
  72. "var": {},
  73. "video": {"poster", "height", "width", "src"},
  74. "wbr": {},
  75. // MathML: https://w3c.github.io/mathml-core/ and https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element
  76. "annotation": {},
  77. "annotation-xml": {},
  78. "maction": {},
  79. "math": {"xmlns"},
  80. "merror": {},
  81. "mfrac": {},
  82. "mi": {},
  83. "mmultiscripts": {},
  84. "mn": {},
  85. "mo": {},
  86. "mover": {},
  87. "mpadded": {},
  88. "mphantom": {},
  89. "mprescripts": {},
  90. "mroot": {},
  91. "mrow": {},
  92. "ms": {},
  93. "mspace": {},
  94. "msqrt": {},
  95. "mstyle": {},
  96. "msub": {},
  97. "msubsup": {},
  98. "msup": {},
  99. "mtable": {},
  100. "mtd": {},
  101. "mtext": {},
  102. "mtr": {},
  103. "munder": {},
  104. "munderover": {},
  105. "semantics": {},
  106. }
  107. )
  108. // Sanitize returns safe HTML.
  109. func Sanitize(baseURL, input string) string {
  110. var buffer strings.Builder
  111. var tagStack []string
  112. var parentTag string
  113. var blockedStack []string
  114. tokenizer := html.NewTokenizer(strings.NewReader(input))
  115. for {
  116. if tokenizer.Next() == html.ErrorToken {
  117. err := tokenizer.Err()
  118. if err == io.EOF {
  119. return buffer.String()
  120. }
  121. return ""
  122. }
  123. token := tokenizer.Token()
  124. // Note: MathML elements are not fully supported by golang.org/x/net/html.
  125. // See https://github.com/golang/net/blob/master/html/atom/gen.go
  126. // and https://github.com/golang/net/blob/master/html/atom/table.go
  127. tagName := token.Data
  128. if tagName == "" {
  129. continue
  130. }
  131. switch token.Type {
  132. case html.TextToken:
  133. if len(blockedStack) > 0 {
  134. continue
  135. }
  136. // An iframe element never has fallback content.
  137. // See https://www.w3.org/TR/2010/WD-html5-20101019/the-iframe-element.html#the-iframe-element
  138. if parentTag == "iframe" {
  139. continue
  140. }
  141. buffer.WriteString(token.String())
  142. case html.StartTagToken:
  143. parentTag = tagName
  144. if isPixelTracker(tagName, token.Attr) {
  145. continue
  146. }
  147. if isBlockedTag(tagName) || slices.ContainsFunc(token.Attr, func(attr html.Attribute) bool { return attr.Key == "hidden" }) {
  148. blockedStack = append(blockedStack, tagName)
  149. continue
  150. }
  151. if len(blockedStack) == 0 && isValidTag(tagName) {
  152. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr)
  153. if hasRequiredAttributes(tagName, attrNames) {
  154. if len(attrNames) > 0 {
  155. // Rewrite the start tag with allowed attributes.
  156. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  157. } else {
  158. // Rewrite the start tag without any attributes.
  159. buffer.WriteString("<" + tagName + ">")
  160. }
  161. tagStack = append(tagStack, tagName)
  162. }
  163. }
  164. case html.EndTagToken:
  165. if len(blockedStack) == 0 {
  166. if isValidTag(tagName) && slices.Contains(tagStack, tagName) {
  167. buffer.WriteString("</" + tagName + ">")
  168. }
  169. } else {
  170. if blockedStack[len(blockedStack)-1] == tagName {
  171. blockedStack = blockedStack[:len(blockedStack)-1]
  172. }
  173. }
  174. case html.SelfClosingTagToken:
  175. if isPixelTracker(tagName, token.Attr) {
  176. continue
  177. }
  178. if len(blockedStack) == 0 && isValidTag(tagName) {
  179. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr)
  180. if hasRequiredAttributes(tagName, attrNames) {
  181. if len(attrNames) > 0 {
  182. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  183. } else {
  184. buffer.WriteString("<" + tagName + "/>")
  185. }
  186. }
  187. }
  188. }
  189. }
  190. }
  191. func sanitizeAttributes(baseURL, tagName string, attributes []html.Attribute) ([]string, string) {
  192. var htmlAttrs, attrNames []string
  193. var err error
  194. var isImageLargerThanLayout bool
  195. var isAnchorLink bool
  196. if tagName == "img" {
  197. imgWidth := getIntegerAttributeValue("width", attributes)
  198. isImageLargerThanLayout = imgWidth > 750
  199. }
  200. for _, attribute := range attributes {
  201. value := attribute.Val
  202. if !isValidAttribute(tagName, attribute.Key) {
  203. continue
  204. }
  205. if (tagName == "img" || tagName == "source") && attribute.Key == "srcset" {
  206. value = sanitizeSrcsetAttr(baseURL, value)
  207. }
  208. if tagName == "img" && (attribute.Key == "width" || attribute.Key == "height") {
  209. if isImageLargerThanLayout || !isPositiveInteger(value) {
  210. continue
  211. }
  212. }
  213. if isExternalResourceAttribute(attribute.Key) {
  214. switch {
  215. case tagName == "iframe":
  216. if !isValidIframeSource(baseURL, attribute.Val) {
  217. continue
  218. }
  219. value = rewriteIframeURL(attribute.Val)
  220. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  221. value = attribute.Val
  222. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  223. value = attribute.Val
  224. isAnchorLink = true
  225. default:
  226. value, err = urllib.AbsoluteURL(baseURL, value)
  227. if err != nil {
  228. continue
  229. }
  230. if !hasValidURIScheme(value) || isBlockedResource(value) {
  231. continue
  232. }
  233. // TODO use feedURL instead of baseURL twice.
  234. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(baseURL, baseURL, value); err == nil {
  235. value = cleanedURL
  236. }
  237. }
  238. }
  239. attrNames = append(attrNames, attribute.Key)
  240. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  241. }
  242. if !isAnchorLink {
  243. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName)
  244. if len(extraAttrNames) > 0 {
  245. attrNames = append(attrNames, extraAttrNames...)
  246. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  247. }
  248. }
  249. return attrNames, strings.Join(htmlAttrs, " ")
  250. }
  251. func getExtraAttributes(tagName string) ([]string, []string) {
  252. switch tagName {
  253. case "a":
  254. return []string{"rel", "target", "referrerpolicy"}, []string{`rel="noopener noreferrer"`, `target="_blank"`, `referrerpolicy="no-referrer"`}
  255. case "video", "audio":
  256. return []string{"controls"}, []string{"controls"}
  257. case "iframe":
  258. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  259. case "img":
  260. return []string{"loading"}, []string{`loading="lazy"`}
  261. default:
  262. return nil, nil
  263. }
  264. }
  265. func isValidTag(tagName string) bool {
  266. _, ok := tagAllowList[tagName]
  267. return ok
  268. }
  269. func isValidAttribute(tagName, attributeName string) bool {
  270. if attributes, ok := tagAllowList[tagName]; ok {
  271. return slices.Contains(attributes, attributeName)
  272. }
  273. return false
  274. }
  275. func isExternalResourceAttribute(attribute string) bool {
  276. switch attribute {
  277. case "src", "href", "poster", "cite":
  278. return true
  279. default:
  280. return false
  281. }
  282. }
  283. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  284. if tagName != "img" {
  285. return false
  286. }
  287. hasHeight := false
  288. hasWidth := false
  289. for _, attribute := range attributes {
  290. if attribute.Val == "1" {
  291. switch attribute.Key {
  292. case "height":
  293. hasHeight = true
  294. case "width":
  295. hasWidth = true
  296. }
  297. }
  298. }
  299. return hasHeight && hasWidth
  300. }
  301. func hasRequiredAttributes(tagName string, attributes []string) bool {
  302. switch tagName {
  303. case "a":
  304. return slices.Contains(attributes, "href")
  305. case "iframe":
  306. return slices.Contains(attributes, "src")
  307. case "source", "img":
  308. return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset")
  309. default:
  310. return true
  311. }
  312. }
  313. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  314. func hasValidURIScheme(src string) bool {
  315. whitelist := []string{
  316. "apt:",
  317. "bitcoin:",
  318. "callto:",
  319. "dav:",
  320. "davs:",
  321. "ed2k://",
  322. "facetime://",
  323. "feed:",
  324. "ftp://",
  325. "geo:",
  326. "gopher://",
  327. "git://",
  328. "http://",
  329. "https://",
  330. "irc://",
  331. "irc6://",
  332. "ircs://",
  333. "itms://",
  334. "itms-apps://",
  335. "magnet:",
  336. "mailto:",
  337. "news:",
  338. "nntp:",
  339. "rtmp://",
  340. "sip:",
  341. "sips:",
  342. "skype:",
  343. "spotify:",
  344. "ssh://",
  345. "sftp://",
  346. "steam://",
  347. "svn://",
  348. "svn+ssh://",
  349. "tel:",
  350. "webcal://",
  351. "xmpp:",
  352. // iOS Apps
  353. "opener://", // https://www.opener.link
  354. "hack://", // https://apps.apple.com/it/app/hack-for-hacker-news-reader/id1464477788?l=en-GB
  355. }
  356. return slices.ContainsFunc(whitelist, func(prefix string) bool {
  357. return strings.HasPrefix(src, prefix)
  358. })
  359. }
  360. func isBlockedResource(src string) bool {
  361. blacklist := []string{
  362. "feedsportal.com",
  363. "api.flattr.com",
  364. "stats.wordpress.com",
  365. "twitter.com/share",
  366. "feeds.feedburner.com",
  367. }
  368. return slices.ContainsFunc(blacklist, func(element string) bool {
  369. return strings.Contains(src, element)
  370. })
  371. }
  372. func isValidIframeSource(baseURL, src string) bool {
  373. whitelist := []string{
  374. "bandcamp.com",
  375. "cdn.embedly.com",
  376. "player.bilibili.com",
  377. "player.twitch.tv",
  378. "player.vimeo.com",
  379. "soundcloud.com",
  380. "vk.com",
  381. "w.soundcloud.com",
  382. "dailymotion.com",
  383. "youtube-nocookie.com",
  384. "youtube.com",
  385. "open.spotify.com",
  386. }
  387. domain := urllib.Domain(src)
  388. // allow iframe from same origin
  389. if urllib.Domain(baseURL) == domain {
  390. return true
  391. }
  392. // allow iframe from custom invidious instance
  393. if config.Opts.InvidiousInstance() == domain {
  394. return true
  395. }
  396. return slices.Contains(whitelist, strings.TrimPrefix(domain, "www."))
  397. }
  398. func rewriteIframeURL(link string) string {
  399. u, err := url.Parse(link)
  400. if err != nil {
  401. return link
  402. }
  403. switch strings.TrimPrefix(u.Hostname(), "www.") {
  404. case "youtube.com":
  405. if strings.HasPrefix(u.Path, "/embed/") {
  406. if len(u.RawQuery) > 0 {
  407. return config.Opts.YouTubeEmbedUrlOverride() + strings.TrimPrefix(u.Path, "/embed/") + "?" + u.RawQuery
  408. }
  409. return config.Opts.YouTubeEmbedUrlOverride() + strings.TrimPrefix(u.Path, "/embed/")
  410. }
  411. case "player.vimeo.com":
  412. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  413. if strings.HasPrefix(u.Path, "/video/") {
  414. if len(u.RawQuery) > 0 {
  415. return link + "&dnt=1"
  416. }
  417. return link + "?dnt=1"
  418. }
  419. }
  420. return link
  421. }
  422. func isBlockedTag(tagName string) bool {
  423. blacklist := []string{
  424. "noscript",
  425. "script",
  426. "style",
  427. }
  428. return slices.Contains(blacklist, tagName)
  429. }
  430. func sanitizeSrcsetAttr(baseURL, value string) string {
  431. imageCandidates := ParseSrcSetAttribute(value)
  432. for _, imageCandidate := range imageCandidates {
  433. if absoluteURL, err := urllib.AbsoluteURL(baseURL, imageCandidate.ImageURL); err == nil {
  434. imageCandidate.ImageURL = absoluteURL
  435. }
  436. }
  437. return imageCandidates.String()
  438. }
  439. func isValidDataAttribute(value string) bool {
  440. var dataAttributeAllowList = []string{
  441. "data:image/avif",
  442. "data:image/apng",
  443. "data:image/png",
  444. "data:image/svg",
  445. "data:image/svg+xml",
  446. "data:image/jpg",
  447. "data:image/jpeg",
  448. "data:image/gif",
  449. "data:image/webp",
  450. }
  451. return slices.ContainsFunc(dataAttributeAllowList, func(prefix string) bool {
  452. return strings.HasPrefix(value, prefix)
  453. })
  454. }
  455. func isPositiveInteger(value string) bool {
  456. if number, err := strconv.Atoi(value); err == nil {
  457. return number > 0
  458. }
  459. return false
  460. }
  461. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  462. for _, attribute := range attributes {
  463. if attribute.Key == name {
  464. number, _ := strconv.Atoi(attribute.Val)
  465. return number
  466. }
  467. }
  468. return 0
  469. }