sanitizer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. "errors"
  6. "io"
  7. "net/url"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "miniflux.app/v2/internal/config"
  12. "miniflux.app/v2/internal/reader/urlcleaner"
  13. "miniflux.app/v2/internal/urllib"
  14. "golang.org/x/net/html"
  15. )
  16. const (
  17. maxDepth = 512 // The maximum allowed depths for nested HTML tags, same was WebKit.
  18. )
  19. var (
  20. allowedHTMLTagsAndAttributes = map[string][]string{
  21. "a": {"href", "title", "id"},
  22. "abbr": {"title"},
  23. "acronym": {"title"},
  24. "aside": {},
  25. "audio": {"src"},
  26. "blockquote": {},
  27. "b": {},
  28. "br": {},
  29. "caption": {},
  30. "cite": {},
  31. "code": {},
  32. "dd": {"id"},
  33. "del": {},
  34. "dfn": {},
  35. "dl": {"id"},
  36. "dt": {"id"},
  37. "em": {},
  38. "figcaption": {},
  39. "figure": {},
  40. "h1": {"id"},
  41. "h2": {"id"},
  42. "h3": {"id"},
  43. "h4": {"id"},
  44. "h5": {"id"},
  45. "h6": {"id"},
  46. "hr": {},
  47. "i": {},
  48. "iframe": {"width", "height", "frameborder", "src", "allowfullscreen"},
  49. "img": {"alt", "title", "src", "srcset", "sizes", "width", "height", "fetchpriority", "decoding"},
  50. "ins": {},
  51. "kbd": {},
  52. "li": {"id"},
  53. "ol": {"id"},
  54. "p": {},
  55. "picture": {},
  56. "pre": {},
  57. "q": {"cite"},
  58. "rp": {},
  59. "rt": {},
  60. "rtc": {},
  61. "ruby": {},
  62. "s": {},
  63. "small": {},
  64. "samp": {},
  65. "source": {"src", "type", "srcset", "sizes", "media"},
  66. "strong": {},
  67. "sub": {},
  68. "sup": {"id"},
  69. "table": {},
  70. "td": {"rowspan", "colspan"},
  71. "tfoot": {},
  72. "th": {"rowspan", "colspan"},
  73. "thead": {},
  74. "time": {"datetime"},
  75. "tr": {},
  76. "u": {},
  77. "ul": {"id"},
  78. "var": {},
  79. "video": {"poster", "height", "width", "src"},
  80. "wbr": {},
  81. // MathML: https://w3c.github.io/mathml-core/ and https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element
  82. "annotation": {},
  83. "annotation-xml": {},
  84. "maction": {},
  85. "math": {"xmlns"},
  86. "merror": {},
  87. "mfrac": {},
  88. "mi": {},
  89. "mmultiscripts": {},
  90. "mn": {},
  91. "mo": {},
  92. "mover": {},
  93. "mpadded": {},
  94. "mphantom": {},
  95. "mprescripts": {},
  96. "mroot": {},
  97. "mrow": {},
  98. "ms": {},
  99. "mspace": {},
  100. "msqrt": {},
  101. "mstyle": {},
  102. "msub": {},
  103. "msubsup": {},
  104. "msup": {},
  105. "mtable": {},
  106. "mtd": {},
  107. "mtext": {},
  108. "mtr": {},
  109. "munder": {},
  110. "munderover": {},
  111. "semantics": {},
  112. }
  113. iframeAllowList = map[string]struct{}{
  114. "bandcamp.com": {},
  115. "cdn.embedly.com": {},
  116. "dailymotion.com": {},
  117. "framatube.org": {},
  118. "open.spotify.com": {},
  119. "player.bilibili.com": {},
  120. "player.twitch.tv": {},
  121. "player.vimeo.com": {},
  122. "soundcloud.com": {},
  123. "vk.com": {},
  124. "w.soundcloud.com": {},
  125. "youtube-nocookie.com": {},
  126. "youtube.com": {},
  127. }
  128. blockedResourceURLSubstrings = []string{
  129. "api.flattr.com",
  130. "www.facebook.com/sharer.php",
  131. "feeds.feedburner.com",
  132. "feedsportal.com",
  133. "linkedin.com/shareArticle",
  134. "pinterest.com/pin/create/button/",
  135. "stats.wordpress.com",
  136. "twitter.com/intent/tweet",
  137. "twitter.com/share",
  138. "x.com/intent/tweet",
  139. "x.com/share",
  140. }
  141. dataAttributeAllowedPrefixes = []string{
  142. "data:image/avif",
  143. "data:image/apng",
  144. "data:image/png",
  145. "data:image/svg",
  146. "data:image/svg+xml",
  147. "data:image/jpg",
  148. "data:image/jpeg",
  149. "data:image/gif",
  150. "data:image/webp",
  151. }
  152. )
  153. // SanitizerOptions holds options for the HTML sanitizer.
  154. type SanitizerOptions struct {
  155. OpenLinksInNewTab bool
  156. }
  157. // SanitizeHTML takes raw HTML input and removes any disallowed tags and attributes.
  158. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  159. var buffer strings.Builder
  160. // Educated guess about how big the sanitized HTML will be,
  161. // to reduce the amount of buffer re-allocations in this function.
  162. estimatedRatio := len(rawHTML) * 3 / 4
  163. buffer.Grow(estimatedRatio)
  164. // We need to surround `rawHTML` with body tags so that html.Parse
  165. // will consider it a valid html document.
  166. doc, err := html.Parse(io.MultiReader(
  167. strings.NewReader("<body>"),
  168. strings.NewReader(rawHTML),
  169. strings.NewReader("</body>"),
  170. ))
  171. if err != nil {
  172. return ""
  173. }
  174. /* The structure of `doc` is always:
  175. <html>
  176. <head>...</head>
  177. <body>..</body>
  178. </html>
  179. */
  180. body := doc.FirstChild.FirstChild.NextSibling
  181. // Errors are a non-issue, so they're handled in filterAndRenderHTML
  182. parsedBaseUrl, _ := url.Parse(baseURL)
  183. for c := body.FirstChild; c != nil; c = c.NextSibling {
  184. // -2 because of `<html><body>…`
  185. if err := filterAndRenderHTML(&buffer, c, parsedBaseUrl, sanitizerOptions, maxDepth-2); err != nil {
  186. return ""
  187. }
  188. }
  189. return buffer.String()
  190. }
  191. func findAllowedIframeSourceDomain(iframeSourceURL string) (string, bool) {
  192. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  193. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  194. return iframeSourceDomain, true
  195. }
  196. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  197. return iframeSourceDomain, true
  198. }
  199. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  200. return iframeSourceDomain, true
  201. }
  202. return "", false
  203. }
  204. func filterAndRenderHTML(buf *strings.Builder, n *html.Node, parsedBaseUrl *url.URL, sanitizerOptions *SanitizerOptions, depth uint) error {
  205. if n == nil {
  206. return nil
  207. }
  208. if depth == 0 {
  209. return errors.New("maximum nested tags limit reached")
  210. }
  211. switch n.Type {
  212. case html.TextNode:
  213. buf.WriteString(html.EscapeString(n.Data))
  214. case html.ElementNode:
  215. tag := n.Data
  216. if shouldIgnoreTag(n, tag) {
  217. return nil
  218. }
  219. _, ok := allowedHTMLTagsAndAttributes[tag]
  220. if !ok {
  221. // The tag isn't allowed, but we're still interested in its content
  222. return filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  223. }
  224. htmlAttributes, hasAllRequiredAttributes := sanitizeAttributes(parsedBaseUrl, tag, n.Attr, sanitizerOptions)
  225. if !hasAllRequiredAttributes {
  226. if tag == "iframe" {
  227. // A blocked iframe should not have its inner content rendered.
  228. return nil
  229. }
  230. // The tag doesn't have every required attributes but we're still interested in its content
  231. return filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  232. }
  233. buf.WriteByte('<')
  234. buf.WriteString(n.Data)
  235. if htmlAttributes != "" {
  236. buf.WriteByte(' ')
  237. buf.WriteString(htmlAttributes)
  238. }
  239. buf.WriteByte('>')
  240. if isSelfContainedTag(tag) {
  241. return nil
  242. }
  243. if tag != "iframe" {
  244. // iframes aren't allowed to have child nodes.
  245. filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  246. }
  247. buf.WriteString("</")
  248. buf.WriteString(n.Data)
  249. buf.WriteByte('>')
  250. default:
  251. }
  252. return nil
  253. }
  254. func filterAndRenderHTMLChildren(buf *strings.Builder, n *html.Node, parsedBaseUrl *url.URL, sanitizerOptions *SanitizerOptions, depth uint) error {
  255. for c := n.FirstChild; c != nil; c = c.NextSibling {
  256. if err := filterAndRenderHTML(buf, c, parsedBaseUrl, sanitizerOptions, depth); err != nil {
  257. return err
  258. }
  259. }
  260. return nil
  261. }
  262. func hasRequiredAttributes(s *mandatoryAttributesStruct, tagName string) bool {
  263. switch tagName {
  264. case "a":
  265. return s.href
  266. case "iframe":
  267. return s.src
  268. case "source", "img":
  269. return s.src || s.srcset
  270. }
  271. return true
  272. }
  273. func isBlockedResource(absoluteURL string) bool {
  274. for _, blockedURL := range blockedResourceURLSubstrings {
  275. if strings.Contains(absoluteURL, blockedURL) {
  276. return true
  277. }
  278. }
  279. return false
  280. }
  281. func isBlockedTag(tagName string) bool {
  282. switch tagName {
  283. case "noscript", "script", "style":
  284. return true
  285. }
  286. return false
  287. }
  288. func isExternalResourceAttribute(attribute string) bool {
  289. switch attribute {
  290. case "src", "href", "poster", "cite":
  291. return true
  292. default:
  293. return false
  294. }
  295. }
  296. func isHidden(n *html.Node) bool {
  297. for _, attr := range n.Attr {
  298. if attr.Key == "hidden" {
  299. return true
  300. }
  301. }
  302. return false
  303. }
  304. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  305. if tagName != "img" {
  306. return false
  307. }
  308. hasHeight := false
  309. hasWidth := false
  310. for _, attribute := range attributes {
  311. if attribute.Val == "1" || attribute.Val == "0" {
  312. switch attribute.Key {
  313. case "height":
  314. hasHeight = true
  315. case "width":
  316. hasWidth = true
  317. }
  318. }
  319. }
  320. return hasHeight && hasWidth
  321. }
  322. func isPositiveInteger(value string) bool {
  323. if value == "" {
  324. return false
  325. }
  326. if number, err := strconv.Atoi(value); err == nil {
  327. return number > 0
  328. }
  329. return false
  330. }
  331. func isSelfContainedTag(tag string) bool {
  332. switch tag {
  333. case "area", "base", "br", "col", "embed", "hr", "img", "input",
  334. "link", "meta", "param", "source", "track", "wbr":
  335. return true
  336. }
  337. return false
  338. }
  339. func isValidDataAttribute(value string) bool {
  340. for _, prefix := range dataAttributeAllowedPrefixes {
  341. if strings.HasPrefix(value, prefix) {
  342. return true
  343. }
  344. }
  345. return false
  346. }
  347. func isValidDecodingValue(value string) bool {
  348. switch value {
  349. case "sync", "async", "auto":
  350. return true
  351. }
  352. return false
  353. }
  354. func isValidFetchPriorityValue(value string) bool {
  355. switch value {
  356. case "high", "low", "auto":
  357. return true
  358. }
  359. return false
  360. }
  361. func rewriteIframeURL(link string) string {
  362. u, err := url.Parse(link)
  363. if err != nil {
  364. return link
  365. }
  366. switch strings.TrimPrefix(u.Hostname(), "www.") {
  367. case "youtube.com":
  368. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  369. if len(u.RawQuery) > 0 {
  370. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  371. }
  372. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  373. }
  374. case "player.vimeo.com":
  375. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  376. if strings.HasPrefix(u.Path, "/video/") {
  377. if len(u.RawQuery) > 0 {
  378. return link + "&dnt=1"
  379. }
  380. return link + "?dnt=1"
  381. }
  382. }
  383. return link
  384. }
  385. type mandatoryAttributesStruct struct {
  386. href bool
  387. src bool
  388. srcset bool
  389. }
  390. func trackAttributes(s *mandatoryAttributesStruct, attributeName string) {
  391. switch attributeName {
  392. case "href":
  393. s.href = true
  394. case "src":
  395. s.src = true
  396. case "srcset":
  397. s.srcset = true
  398. }
  399. }
  400. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) (string, bool) {
  401. var htmlAttrs strings.Builder
  402. // Rough estimate: most attributes are short; ~24 bytes (key + ="value") is
  403. // a reasonable starting point. Avoids early grows for typical elements.
  404. htmlAttrs.Grow(len(attributes) * 24)
  405. // writeAttr appends key="value" to htmlAttrs, prefixing with a single
  406. // space when not the first written attribute. value is HTML-escaped.
  407. writeAttr := func(key, value string) {
  408. htmlAttrs.WriteByte(' ')
  409. htmlAttrs.WriteString(key)
  410. htmlAttrs.WriteString(`="`)
  411. htmlAttrs.WriteString(html.EscapeString(value))
  412. htmlAttrs.WriteByte('"')
  413. }
  414. // Keep track of mandatory attributes for some tags
  415. mandatoryAttributes := mandatoryAttributesStruct{false, false, false}
  416. var isAnchorLink bool
  417. var isYouTubeEmbed bool
  418. // We know the element is present, as the tag was validated in the caller of `sanitizeAttributes`
  419. allowedAttributes := allowedHTMLTagsAndAttributes[tagName]
  420. for _, attribute := range attributes {
  421. if !slices.Contains(allowedAttributes, attribute.Key) {
  422. continue
  423. }
  424. value := attribute.Val
  425. switch tagName {
  426. case "math":
  427. if attribute.Key == "xmlns" {
  428. if value != "http://www.w3.org/1998/Math/MathML" {
  429. value = "http://www.w3.org/1998/Math/MathML"
  430. }
  431. }
  432. case "img":
  433. switch attribute.Key {
  434. case "fetchpriority":
  435. if !isValidFetchPriorityValue(value) {
  436. continue
  437. }
  438. case "decoding":
  439. if !isValidDecodingValue(value) {
  440. continue
  441. }
  442. case "width", "height":
  443. if !isPositiveInteger(value) {
  444. continue
  445. }
  446. case "srcset":
  447. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  448. if value == "" {
  449. continue
  450. }
  451. }
  452. case "source":
  453. if attribute.Key == "srcset" {
  454. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  455. if value == "" {
  456. continue
  457. }
  458. }
  459. }
  460. if isExternalResourceAttribute(attribute.Key) {
  461. switch {
  462. case tagName == "iframe":
  463. iframeSourceDomain, trustedIframeDomain := findAllowedIframeSourceDomain(attribute.Val)
  464. if !trustedIframeDomain {
  465. return "", false
  466. }
  467. value = rewriteIframeURL(attribute.Val)
  468. if iframeSourceDomain == "youtube.com" || iframeSourceDomain == "youtube-nocookie.com" {
  469. isYouTubeEmbed = true
  470. }
  471. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  472. value = attribute.Val
  473. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  474. value = attribute.Val
  475. isAnchorLink = true
  476. default:
  477. if isBlockedResource(value) {
  478. return "", false
  479. }
  480. var err error
  481. value, err = urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseUrl, value)
  482. if err != nil {
  483. continue
  484. }
  485. if !HasValidURIScheme(value) {
  486. continue
  487. }
  488. // Skip the parse + RemoveTrackingParameters round trip when there
  489. // is no query string to clean, which is common for <img>.
  490. if strings.IndexByte(value, '?') >= 0 {
  491. parsedValueUrl, _ := url.Parse(value)
  492. // TODO use feedURL instead of baseURL twice.
  493. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  494. value = cleanedURL
  495. }
  496. }
  497. }
  498. }
  499. trackAttributes(&mandatoryAttributes, attribute.Key)
  500. writeAttr(attribute.Key, value)
  501. }
  502. if !hasRequiredAttributes(&mandatoryAttributes, tagName) {
  503. return "", false
  504. }
  505. if !isAnchorLink {
  506. switch tagName {
  507. case "a":
  508. writeAttr("rel", "noopener noreferrer")
  509. writeAttr("referrerpolicy", "no-referrer")
  510. if sanitizerOptions.OpenLinksInNewTab {
  511. writeAttr("target", "_blank")
  512. }
  513. case "video", "audio":
  514. htmlAttrs.WriteString(" controls")
  515. case "iframe":
  516. writeAttr("sandbox", "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox")
  517. writeAttr("loading", "lazy")
  518. // Note: the referrerpolicy seems to be required to avoid YouTube error 153 video player configuration error
  519. // See https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-player-api-client-identity
  520. if isYouTubeEmbed {
  521. writeAttr("referrerpolicy", "strict-origin-when-cross-origin")
  522. }
  523. case "img":
  524. writeAttr("loading", "lazy")
  525. }
  526. }
  527. return strings.TrimLeft(htmlAttrs.String(), " "), true
  528. }
  529. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  530. candidates := ParseSrcSetAttribute(value)
  531. if len(candidates) == 0 {
  532. return ""
  533. }
  534. sanitizedCandidates := make([]*imageCandidate, 0, len(candidates))
  535. for _, imageCandidate := range candidates {
  536. absoluteURL, err := urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseURL, imageCandidate.ImageURL)
  537. if err != nil {
  538. continue
  539. }
  540. if !HasValidURIScheme(absoluteURL) || isBlockedResource(absoluteURL) {
  541. continue
  542. }
  543. imageCandidate.ImageURL = absoluteURL
  544. sanitizedCandidates = append(sanitizedCandidates, imageCandidate)
  545. }
  546. return imageCandidates(sanitizedCandidates).String()
  547. }
  548. func shouldIgnoreTag(n *html.Node, tag string) bool {
  549. if isPixelTracker(tag, n.Attr) {
  550. return true
  551. }
  552. if isBlockedTag(tag) {
  553. return true
  554. }
  555. if isHidden(n) {
  556. return true
  557. }
  558. return false
  559. }