sanitizer.go 16 KB

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