sanitizer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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", "fetchpriority", "decoding"},
  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. type SanitizerOptions struct {
  109. OpenLinksInNewTab bool
  110. }
  111. func SanitizeHTMLWithDefaultOptions(baseURL, rawHTML string) string {
  112. return SanitizeHTML(baseURL, rawHTML, &SanitizerOptions{
  113. OpenLinksInNewTab: true,
  114. })
  115. }
  116. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  117. var buffer strings.Builder
  118. var tagStack []string
  119. var parentTag string
  120. var blockedStack []string
  121. tokenizer := html.NewTokenizer(strings.NewReader(rawHTML))
  122. for {
  123. if tokenizer.Next() == html.ErrorToken {
  124. err := tokenizer.Err()
  125. if err == io.EOF {
  126. return buffer.String()
  127. }
  128. return ""
  129. }
  130. token := tokenizer.Token()
  131. // Note: MathML elements are not fully supported by golang.org/x/net/html.
  132. // See https://github.com/golang/net/blob/master/html/atom/gen.go
  133. // and https://github.com/golang/net/blob/master/html/atom/table.go
  134. tagName := token.Data
  135. if tagName == "" {
  136. continue
  137. }
  138. switch token.Type {
  139. case html.TextToken:
  140. if len(blockedStack) > 0 {
  141. continue
  142. }
  143. // An iframe element never has fallback content.
  144. // See https://www.w3.org/TR/2010/WD-html5-20101019/the-iframe-element.html#the-iframe-element
  145. if parentTag == "iframe" {
  146. continue
  147. }
  148. buffer.WriteString(token.String())
  149. case html.StartTagToken:
  150. parentTag = tagName
  151. if isPixelTracker(tagName, token.Attr) {
  152. continue
  153. }
  154. if isBlockedTag(tagName) || slices.ContainsFunc(token.Attr, func(attr html.Attribute) bool { return attr.Key == "hidden" }) {
  155. blockedStack = append(blockedStack, tagName)
  156. continue
  157. }
  158. if len(blockedStack) == 0 && isValidTag(tagName) {
  159. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr, sanitizerOptions)
  160. if hasRequiredAttributes(tagName, attrNames) {
  161. if len(attrNames) > 0 {
  162. // Rewrite the start tag with allowed attributes.
  163. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  164. } else {
  165. // Rewrite the start tag without any attributes.
  166. buffer.WriteString("<" + tagName + ">")
  167. }
  168. tagStack = append(tagStack, tagName)
  169. }
  170. }
  171. case html.EndTagToken:
  172. if len(blockedStack) == 0 {
  173. if isValidTag(tagName) && slices.Contains(tagStack, tagName) {
  174. buffer.WriteString("</" + tagName + ">")
  175. }
  176. } else {
  177. if blockedStack[len(blockedStack)-1] == tagName {
  178. blockedStack = blockedStack[:len(blockedStack)-1]
  179. }
  180. }
  181. case html.SelfClosingTagToken:
  182. if isPixelTracker(tagName, token.Attr) {
  183. continue
  184. }
  185. if len(blockedStack) == 0 && isValidTag(tagName) {
  186. attrNames, htmlAttributes := sanitizeAttributes(baseURL, tagName, token.Attr, sanitizerOptions)
  187. if hasRequiredAttributes(tagName, attrNames) {
  188. if len(attrNames) > 0 {
  189. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  190. } else {
  191. buffer.WriteString("<" + tagName + "/>")
  192. }
  193. }
  194. }
  195. }
  196. }
  197. }
  198. func sanitizeAttributes(baseURL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) ([]string, string) {
  199. var htmlAttrs, attrNames []string
  200. var err error
  201. var isImageLargerThanLayout bool
  202. var isAnchorLink bool
  203. if tagName == "img" {
  204. imgWidth := getIntegerAttributeValue("width", attributes)
  205. isImageLargerThanLayout = imgWidth > 750
  206. }
  207. for _, attribute := range attributes {
  208. value := attribute.Val
  209. if !isValidAttribute(tagName, attribute.Key) {
  210. continue
  211. }
  212. if tagName == "math" && attribute.Key == "xmlns" && value != "http://www.w3.org/1998/Math/MathML" {
  213. value = "http://www.w3.org/1998/Math/MathML"
  214. }
  215. if tagName == "img" && attribute.Key == "fetchpriority" {
  216. if !isValidFetchPriorityValue(value) {
  217. continue
  218. }
  219. }
  220. if tagName == "img" && attribute.Key == "decoding" {
  221. if !isValidDecodingValue(value) {
  222. continue
  223. }
  224. }
  225. if (tagName == "img" || tagName == "source") && attribute.Key == "srcset" {
  226. value = sanitizeSrcsetAttr(baseURL, value)
  227. }
  228. if tagName == "img" && (attribute.Key == "width" || attribute.Key == "height") {
  229. if isImageLargerThanLayout || !isPositiveInteger(value) {
  230. continue
  231. }
  232. }
  233. if isExternalResourceAttribute(attribute.Key) {
  234. switch {
  235. case tagName == "iframe":
  236. if !isValidIframeSource(baseURL, attribute.Val) {
  237. continue
  238. }
  239. value = rewriteIframeURL(attribute.Val)
  240. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  241. value = attribute.Val
  242. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  243. value = attribute.Val
  244. isAnchorLink = true
  245. default:
  246. value, err = urllib.AbsoluteURL(baseURL, value)
  247. if err != nil {
  248. continue
  249. }
  250. if !hasValidURIScheme(value) || isBlockedResource(value) {
  251. continue
  252. }
  253. // TODO use feedURL instead of baseURL twice.
  254. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(baseURL, baseURL, value); err == nil {
  255. value = cleanedURL
  256. }
  257. }
  258. }
  259. attrNames = append(attrNames, attribute.Key)
  260. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  261. }
  262. if !isAnchorLink {
  263. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName, sanitizerOptions)
  264. if len(extraAttrNames) > 0 {
  265. attrNames = append(attrNames, extraAttrNames...)
  266. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  267. }
  268. }
  269. return attrNames, strings.Join(htmlAttrs, " ")
  270. }
  271. func getExtraAttributes(tagName string, sanitizerOptions *SanitizerOptions) ([]string, []string) {
  272. switch tagName {
  273. case "a":
  274. attributeNames := []string{"rel", "referrerpolicy"}
  275. htmlAttributes := []string{`rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`}
  276. if sanitizerOptions.OpenLinksInNewTab {
  277. attributeNames = append(attributeNames, "target")
  278. htmlAttributes = append(htmlAttributes, `target="_blank"`)
  279. }
  280. return attributeNames, htmlAttributes
  281. case "video", "audio":
  282. return []string{"controls"}, []string{"controls"}
  283. case "iframe":
  284. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  285. case "img":
  286. return []string{"loading"}, []string{`loading="lazy"`}
  287. default:
  288. return nil, nil
  289. }
  290. }
  291. func isValidTag(tagName string) bool {
  292. _, ok := tagAllowList[tagName]
  293. return ok
  294. }
  295. func isValidAttribute(tagName, attributeName string) bool {
  296. if attributes, ok := tagAllowList[tagName]; ok {
  297. return slices.Contains(attributes, attributeName)
  298. }
  299. return false
  300. }
  301. func isExternalResourceAttribute(attribute string) bool {
  302. switch attribute {
  303. case "src", "href", "poster", "cite":
  304. return true
  305. default:
  306. return false
  307. }
  308. }
  309. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  310. if tagName != "img" {
  311. return false
  312. }
  313. hasHeight := false
  314. hasWidth := false
  315. for _, attribute := range attributes {
  316. if attribute.Val == "1" {
  317. switch attribute.Key {
  318. case "height":
  319. hasHeight = true
  320. case "width":
  321. hasWidth = true
  322. }
  323. }
  324. }
  325. return hasHeight && hasWidth
  326. }
  327. func hasRequiredAttributes(tagName string, attributes []string) bool {
  328. switch tagName {
  329. case "a":
  330. return slices.Contains(attributes, "href")
  331. case "iframe":
  332. return slices.Contains(attributes, "src")
  333. case "source", "img":
  334. return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset")
  335. default:
  336. return true
  337. }
  338. }
  339. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  340. func hasValidURIScheme(src string) bool {
  341. whitelist := []string{
  342. "apt:",
  343. "bitcoin:",
  344. "callto:",
  345. "dav:",
  346. "davs:",
  347. "ed2k://",
  348. "facetime://",
  349. "feed:",
  350. "ftp://",
  351. "geo:",
  352. "gopher://",
  353. "git://",
  354. "http://",
  355. "https://",
  356. "irc://",
  357. "irc6://",
  358. "ircs://",
  359. "itms://",
  360. "itms-apps://",
  361. "magnet:",
  362. "mailto:",
  363. "news:",
  364. "nntp:",
  365. "rtmp://",
  366. "sip:",
  367. "sips:",
  368. "skype:",
  369. "spotify:",
  370. "ssh://",
  371. "sftp://",
  372. "steam://",
  373. "svn://",
  374. "svn+ssh://",
  375. "tel:",
  376. "webcal://",
  377. "xmpp:",
  378. // iOS Apps
  379. "opener://", // https://www.opener.link
  380. "hack://", // https://apps.apple.com/it/app/hack-for-hacker-news-reader/id1464477788?l=en-GB
  381. }
  382. return slices.ContainsFunc(whitelist, func(prefix string) bool {
  383. return strings.HasPrefix(src, prefix)
  384. })
  385. }
  386. func isBlockedResource(src string) bool {
  387. blacklist := []string{
  388. "feedsportal.com",
  389. "api.flattr.com",
  390. "stats.wordpress.com",
  391. "twitter.com/share",
  392. "feeds.feedburner.com",
  393. }
  394. return slices.ContainsFunc(blacklist, func(element string) bool {
  395. return strings.Contains(src, element)
  396. })
  397. }
  398. func isValidIframeSource(baseURL, src string) bool {
  399. whitelist := []string{
  400. "bandcamp.com",
  401. "cdn.embedly.com",
  402. "player.bilibili.com",
  403. "player.twitch.tv",
  404. "player.vimeo.com",
  405. "soundcloud.com",
  406. "vk.com",
  407. "w.soundcloud.com",
  408. "dailymotion.com",
  409. "youtube-nocookie.com",
  410. "youtube.com",
  411. "open.spotify.com",
  412. }
  413. domain := urllib.Domain(src)
  414. // allow iframe from same origin
  415. if urllib.Domain(baseURL) == domain {
  416. return true
  417. }
  418. // allow iframe from custom invidious instance
  419. if config.Opts.InvidiousInstance() == domain {
  420. return true
  421. }
  422. return slices.Contains(whitelist, strings.TrimPrefix(domain, "www."))
  423. }
  424. func rewriteIframeURL(link string) string {
  425. u, err := url.Parse(link)
  426. if err != nil {
  427. return link
  428. }
  429. switch strings.TrimPrefix(u.Hostname(), "www.") {
  430. case "youtube.com":
  431. if strings.HasPrefix(u.Path, "/embed/") {
  432. if len(u.RawQuery) > 0 {
  433. return config.Opts.YouTubeEmbedUrlOverride() + strings.TrimPrefix(u.Path, "/embed/") + "?" + u.RawQuery
  434. }
  435. return config.Opts.YouTubeEmbedUrlOverride() + strings.TrimPrefix(u.Path, "/embed/")
  436. }
  437. case "player.vimeo.com":
  438. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  439. if strings.HasPrefix(u.Path, "/video/") {
  440. if len(u.RawQuery) > 0 {
  441. return link + "&dnt=1"
  442. }
  443. return link + "?dnt=1"
  444. }
  445. }
  446. return link
  447. }
  448. func isBlockedTag(tagName string) bool {
  449. blacklist := []string{
  450. "noscript",
  451. "script",
  452. "style",
  453. }
  454. return slices.Contains(blacklist, tagName)
  455. }
  456. func sanitizeSrcsetAttr(baseURL, value string) string {
  457. imageCandidates := ParseSrcSetAttribute(value)
  458. for _, imageCandidate := range imageCandidates {
  459. if absoluteURL, err := urllib.AbsoluteURL(baseURL, imageCandidate.ImageURL); err == nil {
  460. imageCandidate.ImageURL = absoluteURL
  461. }
  462. }
  463. return imageCandidates.String()
  464. }
  465. func isValidDataAttribute(value string) bool {
  466. var dataAttributeAllowList = []string{
  467. "data:image/avif",
  468. "data:image/apng",
  469. "data:image/png",
  470. "data:image/svg",
  471. "data:image/svg+xml",
  472. "data:image/jpg",
  473. "data:image/jpeg",
  474. "data:image/gif",
  475. "data:image/webp",
  476. }
  477. return slices.ContainsFunc(dataAttributeAllowList, func(prefix string) bool {
  478. return strings.HasPrefix(value, prefix)
  479. })
  480. }
  481. func isPositiveInteger(value string) bool {
  482. if number, err := strconv.Atoi(value); err == nil {
  483. return number > 0
  484. }
  485. return false
  486. }
  487. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  488. for _, attribute := range attributes {
  489. if attribute.Key == name {
  490. number, _ := strconv.Atoi(attribute.Val)
  491. return number
  492. }
  493. }
  494. return 0
  495. }
  496. func isValidFetchPriorityValue(value string) bool {
  497. allowedValues := []string{"high", "low", "auto"}
  498. return slices.Contains(allowedValues, value)
  499. }
  500. func isValidDecodingValue(value string) bool {
  501. allowedValues := []string{"sync", "async", "auto"}
  502. return slices.Contains(allowedValues, value)
  503. }