sanitizer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  142. validURISchemes = []string{
  143. // Most commong schemes on top.
  144. "https:",
  145. "http:",
  146. // Then the rest.
  147. "apt:",
  148. "bitcoin:",
  149. "callto:",
  150. "dav:",
  151. "davs:",
  152. "ed2k:",
  153. "facetime:",
  154. "feed:",
  155. "ftp:",
  156. "geo:",
  157. "git:",
  158. "gopher:",
  159. "irc:",
  160. "irc6:",
  161. "ircs:",
  162. "itms-apps:",
  163. "itms:",
  164. "magnet:",
  165. "mailto:",
  166. "news:",
  167. "nntp:",
  168. "rtmp:",
  169. "sftp:",
  170. "sip:",
  171. "sips:",
  172. "skype:",
  173. "spotify:",
  174. "ssh:",
  175. "steam:",
  176. "svn:",
  177. "svn+ssh:",
  178. "tel:",
  179. "webcal:",
  180. "xmpp:",
  181. // iOS Apps
  182. "opener:", // https://www.opener.link
  183. "hack:", // https://apps.apple.com/it/app/hack-for-hacker-news-reader/id1464477788?l=en-GB
  184. }
  185. dataAttributeAllowedPrefixes = []string{
  186. "data:image/avif",
  187. "data:image/apng",
  188. "data:image/png",
  189. "data:image/svg",
  190. "data:image/svg+xml",
  191. "data:image/jpg",
  192. "data:image/jpeg",
  193. "data:image/gif",
  194. "data:image/webp",
  195. }
  196. )
  197. // SanitizerOptions holds options for the HTML sanitizer.
  198. type SanitizerOptions struct {
  199. OpenLinksInNewTab bool
  200. }
  201. // SanitizeHTML takes raw HTML input and removes any disallowed tags and attributes.
  202. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  203. var buffer strings.Builder
  204. // Educated guess about how big the sanitized HTML will be,
  205. // to reduce the amount of buffer re-allocations in this function.
  206. estimatedRatio := len(rawHTML) * 3 / 4
  207. buffer.Grow(estimatedRatio)
  208. // We need to surround `rawHTML` with body tags so that html.Parse
  209. // will consider it a valid html document.
  210. doc, err := html.Parse(io.MultiReader(
  211. strings.NewReader("<body>"),
  212. strings.NewReader(rawHTML),
  213. strings.NewReader("</body>"),
  214. ))
  215. if err != nil {
  216. return ""
  217. }
  218. /* The structure of `doc` is always:
  219. <html>
  220. <head>...</head>
  221. <body>..</body>
  222. </html>
  223. */
  224. body := doc.FirstChild.FirstChild.NextSibling
  225. // Errors are a non-issue, so they're handled in filterAndRenderHTML
  226. parsedBaseUrl, _ := url.Parse(baseURL)
  227. for c := body.FirstChild; c != nil; c = c.NextSibling {
  228. // -2 because of `<html><body>…`
  229. if err := filterAndRenderHTML(&buffer, c, parsedBaseUrl, sanitizerOptions, maxDepth-2); err != nil {
  230. return ""
  231. }
  232. }
  233. return buffer.String()
  234. }
  235. func findAllowedIframeSourceDomain(iframeSourceURL string) (string, bool) {
  236. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  237. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  238. return iframeSourceDomain, true
  239. }
  240. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  241. return iframeSourceDomain, true
  242. }
  243. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  244. return iframeSourceDomain, true
  245. }
  246. return "", false
  247. }
  248. func filterAndRenderHTML(buf *strings.Builder, n *html.Node, parsedBaseUrl *url.URL, sanitizerOptions *SanitizerOptions, depth uint) error {
  249. if n == nil {
  250. return nil
  251. }
  252. if depth == 0 {
  253. return errors.New("maximum nested tags limit reached")
  254. }
  255. switch n.Type {
  256. case html.TextNode:
  257. buf.WriteString(html.EscapeString(n.Data))
  258. case html.ElementNode:
  259. tag := n.Data
  260. if shouldIgnoreTag(n, tag) {
  261. return nil
  262. }
  263. _, ok := allowedHTMLTagsAndAttributes[tag]
  264. if !ok {
  265. // The tag isn't allowed, but we're still interested in its content
  266. return filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  267. }
  268. htmlAttributes, hasAllRequiredAttributes := sanitizeAttributes(parsedBaseUrl, tag, n.Attr, sanitizerOptions)
  269. if !hasAllRequiredAttributes {
  270. if tag == "iframe" {
  271. // A blocked iframe should not have its inner content rendered.
  272. return nil
  273. }
  274. // The tag doesn't have every required attributes but we're still interested in its content
  275. return filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  276. }
  277. buf.WriteByte('<')
  278. buf.WriteString(n.Data)
  279. if htmlAttributes != "" {
  280. buf.WriteByte(' ')
  281. buf.WriteString(htmlAttributes)
  282. }
  283. buf.WriteByte('>')
  284. if isSelfContainedTag(tag) {
  285. return nil
  286. }
  287. if tag != "iframe" {
  288. // iframes aren't allowed to have child nodes.
  289. filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  290. }
  291. buf.WriteString("</")
  292. buf.WriteString(n.Data)
  293. buf.WriteByte('>')
  294. default:
  295. }
  296. return nil
  297. }
  298. func filterAndRenderHTMLChildren(buf *strings.Builder, n *html.Node, parsedBaseUrl *url.URL, sanitizerOptions *SanitizerOptions, depth uint) error {
  299. for c := n.FirstChild; c != nil; c = c.NextSibling {
  300. if err := filterAndRenderHTML(buf, c, parsedBaseUrl, sanitizerOptions, depth); err != nil {
  301. return err
  302. }
  303. }
  304. return nil
  305. }
  306. func hasRequiredAttributes(s *mandatoryAttributesStruct, tagName string) bool {
  307. switch tagName {
  308. case "a":
  309. return s.href
  310. case "iframe":
  311. return s.src
  312. case "source", "img":
  313. return s.src || s.srcset
  314. }
  315. return true
  316. }
  317. func hasValidURIScheme(absoluteURL string) bool {
  318. for _, scheme := range validURISchemes {
  319. if strings.HasPrefix(absoluteURL, scheme) {
  320. return true
  321. }
  322. }
  323. return false
  324. }
  325. func isBlockedResource(absoluteURL string) bool {
  326. for _, blockedURL := range blockedResourceURLSubstrings {
  327. if strings.Contains(absoluteURL, blockedURL) {
  328. return true
  329. }
  330. }
  331. return false
  332. }
  333. func isBlockedTag(tagName string) bool {
  334. switch tagName {
  335. case "noscript", "script", "style":
  336. return true
  337. }
  338. return false
  339. }
  340. func isExternalResourceAttribute(attribute string) bool {
  341. switch attribute {
  342. case "src", "href", "poster", "cite":
  343. return true
  344. default:
  345. return false
  346. }
  347. }
  348. func isHidden(n *html.Node) bool {
  349. for _, attr := range n.Attr {
  350. if attr.Key == "hidden" {
  351. return true
  352. }
  353. }
  354. return false
  355. }
  356. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  357. if tagName != "img" {
  358. return false
  359. }
  360. hasHeight := false
  361. hasWidth := false
  362. for _, attribute := range attributes {
  363. if attribute.Val == "1" || attribute.Val == "0" {
  364. switch attribute.Key {
  365. case "height":
  366. hasHeight = true
  367. case "width":
  368. hasWidth = true
  369. }
  370. }
  371. }
  372. return hasHeight && hasWidth
  373. }
  374. func isPositiveInteger(value string) bool {
  375. if value == "" {
  376. return false
  377. }
  378. if number, err := strconv.Atoi(value); err == nil {
  379. return number > 0
  380. }
  381. return false
  382. }
  383. func isSelfContainedTag(tag string) bool {
  384. switch tag {
  385. case "area", "base", "br", "col", "embed", "hr", "img", "input",
  386. "link", "meta", "param", "source", "track", "wbr":
  387. return true
  388. }
  389. return false
  390. }
  391. func isValidDataAttribute(value string) bool {
  392. for _, prefix := range dataAttributeAllowedPrefixes {
  393. if strings.HasPrefix(value, prefix) {
  394. return true
  395. }
  396. }
  397. return false
  398. }
  399. func isValidDecodingValue(value string) bool {
  400. switch value {
  401. case "sync", "async", "auto":
  402. return true
  403. }
  404. return false
  405. }
  406. func isValidFetchPriorityValue(value string) bool {
  407. switch value {
  408. case "high", "low", "auto":
  409. return true
  410. }
  411. return false
  412. }
  413. func rewriteIframeURL(link string) string {
  414. u, err := url.Parse(link)
  415. if err != nil {
  416. return link
  417. }
  418. switch strings.TrimPrefix(u.Hostname(), "www.") {
  419. case "youtube.com":
  420. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  421. if len(u.RawQuery) > 0 {
  422. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  423. }
  424. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  425. }
  426. case "player.vimeo.com":
  427. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  428. if strings.HasPrefix(u.Path, "/video/") {
  429. if len(u.RawQuery) > 0 {
  430. return link + "&dnt=1"
  431. }
  432. return link + "?dnt=1"
  433. }
  434. }
  435. return link
  436. }
  437. type mandatoryAttributesStruct struct {
  438. href bool
  439. src bool
  440. srcset bool
  441. }
  442. func trackAttributes(s *mandatoryAttributesStruct, attributeName string) {
  443. switch attributeName {
  444. case "href":
  445. s.href = true
  446. case "src":
  447. s.src = true
  448. case "srcset":
  449. s.srcset = true
  450. }
  451. }
  452. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) (string, bool) {
  453. htmlAttrs := make([]string, 0, len(attributes))
  454. // Keep track of mandatory attributes for some tags
  455. mandatoryAttributes := mandatoryAttributesStruct{false, false, false}
  456. var isAnchorLink bool
  457. var isYouTubeEmbed bool
  458. // We know the element is present, as the tag was validated in the caller of `sanitizeAttributes`
  459. allowedAttributes := allowedHTMLTagsAndAttributes[tagName]
  460. for _, attribute := range attributes {
  461. if !slices.Contains(allowedAttributes, attribute.Key) {
  462. continue
  463. }
  464. value := attribute.Val
  465. switch tagName {
  466. case "math":
  467. if attribute.Key == "xmlns" {
  468. if value != "http://www.w3.org/1998/Math/MathML" {
  469. value = "http://www.w3.org/1998/Math/MathML"
  470. }
  471. }
  472. case "img":
  473. switch attribute.Key {
  474. case "fetchpriority":
  475. if !isValidFetchPriorityValue(value) {
  476. continue
  477. }
  478. case "decoding":
  479. if !isValidDecodingValue(value) {
  480. continue
  481. }
  482. case "width", "height":
  483. if !isPositiveInteger(value) {
  484. continue
  485. }
  486. case "srcset":
  487. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  488. if value == "" {
  489. continue
  490. }
  491. }
  492. case "source":
  493. if attribute.Key == "srcset" {
  494. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  495. if value == "" {
  496. continue
  497. }
  498. }
  499. }
  500. if isExternalResourceAttribute(attribute.Key) {
  501. switch {
  502. case tagName == "iframe":
  503. iframeSourceDomain, trustedIframeDomain := findAllowedIframeSourceDomain(attribute.Val)
  504. if !trustedIframeDomain {
  505. return "", false
  506. }
  507. value = rewriteIframeURL(attribute.Val)
  508. if iframeSourceDomain == "youtube.com" || iframeSourceDomain == "youtube-nocookie.com" {
  509. isYouTubeEmbed = true
  510. }
  511. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  512. value = attribute.Val
  513. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  514. value = attribute.Val
  515. isAnchorLink = true
  516. default:
  517. if isBlockedResource(value) {
  518. return "", false
  519. }
  520. var err error
  521. value, err = urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseUrl, value)
  522. if err != nil {
  523. continue
  524. }
  525. if !hasValidURIScheme(value) {
  526. continue
  527. }
  528. // TODO use feedURL instead of baseURL twice.
  529. parsedValueUrl, _ := url.Parse(value)
  530. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  531. value = cleanedURL
  532. }
  533. }
  534. }
  535. trackAttributes(&mandatoryAttributes, attribute.Key)
  536. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  537. }
  538. if !hasRequiredAttributes(&mandatoryAttributes, tagName) {
  539. return "", false
  540. }
  541. if !isAnchorLink {
  542. switch tagName {
  543. case "a":
  544. htmlAttrs = append(htmlAttrs, `rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`)
  545. if sanitizerOptions.OpenLinksInNewTab {
  546. htmlAttrs = append(htmlAttrs, `target="_blank"`)
  547. }
  548. case "video", "audio":
  549. htmlAttrs = append(htmlAttrs, "controls")
  550. case "iframe":
  551. htmlAttrs = append(htmlAttrs, `sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`)
  552. // Note: the referrerpolicy seems to be required to avoid YouTube error 153 video player configuration error
  553. // See https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-player-api-client-identity
  554. if isYouTubeEmbed {
  555. htmlAttrs = append(htmlAttrs, `referrerpolicy="strict-origin-when-cross-origin"`)
  556. }
  557. case "img":
  558. htmlAttrs = append(htmlAttrs, `loading="lazy"`)
  559. }
  560. }
  561. return strings.Join(htmlAttrs, " "), true
  562. }
  563. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  564. candidates := ParseSrcSetAttribute(value)
  565. if len(candidates) == 0 {
  566. return ""
  567. }
  568. sanitizedCandidates := make([]*imageCandidate, 0, len(candidates))
  569. for _, imageCandidate := range candidates {
  570. absoluteURL, err := urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseURL, imageCandidate.ImageURL)
  571. if err != nil {
  572. continue
  573. }
  574. if !hasValidURIScheme(absoluteURL) || isBlockedResource(absoluteURL) {
  575. continue
  576. }
  577. imageCandidate.ImageURL = absoluteURL
  578. sanitizedCandidates = append(sanitizedCandidates, imageCandidate)
  579. }
  580. return imageCandidates(sanitizedCandidates).String()
  581. }
  582. func shouldIgnoreTag(n *html.Node, tag string) bool {
  583. if isPixelTracker(tag, n.Attr) {
  584. return true
  585. }
  586. if isBlockedTag(tag) {
  587. return true
  588. }
  589. if isHidden(n) {
  590. return true
  591. }
  592. return false
  593. }