sanitizer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. if tag == "iframe" {
  265. // A blocked iframe should not have its inner content rendered.
  266. return nil
  267. }
  268. // The tag doesn't have every required attributes but we're still interested in its content
  269. return filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  270. }
  271. buf.WriteByte('<')
  272. buf.WriteString(n.Data)
  273. if htmlAttributes != "" {
  274. buf.WriteByte(' ')
  275. buf.WriteString(htmlAttributes)
  276. }
  277. buf.WriteByte('>')
  278. if isSelfContainedTag(tag) {
  279. return nil
  280. }
  281. if tag != "iframe" {
  282. // iframes aren't allowed to have child nodes.
  283. filterAndRenderHTMLChildren(buf, n, parsedBaseUrl, sanitizerOptions, depth-1)
  284. }
  285. buf.WriteString("</")
  286. buf.WriteString(n.Data)
  287. buf.WriteByte('>')
  288. default:
  289. }
  290. return nil
  291. }
  292. func filterAndRenderHTMLChildren(buf *strings.Builder, n *html.Node, parsedBaseUrl *url.URL, sanitizerOptions *SanitizerOptions, depth uint) error {
  293. for c := n.FirstChild; c != nil; c = c.NextSibling {
  294. if err := filterAndRenderHTML(buf, c, parsedBaseUrl, sanitizerOptions, depth); err != nil {
  295. return err
  296. }
  297. }
  298. return nil
  299. }
  300. func hasRequiredAttributes(s *mandatoryAttributesStruct, tagName string) bool {
  301. switch tagName {
  302. case "a":
  303. return s.href
  304. case "iframe":
  305. return s.src
  306. case "source", "img":
  307. return s.src || s.srcset
  308. }
  309. return true
  310. }
  311. func hasValidURIScheme(absoluteURL string) bool {
  312. for _, scheme := range validURISchemes {
  313. if strings.HasPrefix(absoluteURL, scheme) {
  314. return true
  315. }
  316. }
  317. return false
  318. }
  319. func isBlockedResource(absoluteURL string) bool {
  320. for _, blockedURL := range blockedResourceURLSubstrings {
  321. if strings.Contains(absoluteURL, blockedURL) {
  322. return true
  323. }
  324. }
  325. return false
  326. }
  327. func isBlockedTag(tagName string) bool {
  328. switch tagName {
  329. case "noscript", "script", "style":
  330. return true
  331. }
  332. return false
  333. }
  334. func isExternalResourceAttribute(attribute string) bool {
  335. switch attribute {
  336. case "src", "href", "poster", "cite":
  337. return true
  338. default:
  339. return false
  340. }
  341. }
  342. func isHidden(n *html.Node) bool {
  343. for _, attr := range n.Attr {
  344. if attr.Key == "hidden" {
  345. return true
  346. }
  347. }
  348. return false
  349. }
  350. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  351. if tagName != "img" {
  352. return false
  353. }
  354. hasHeight := false
  355. hasWidth := false
  356. for _, attribute := range attributes {
  357. if attribute.Val == "1" || attribute.Val == "0" {
  358. switch attribute.Key {
  359. case "height":
  360. hasHeight = true
  361. case "width":
  362. hasWidth = true
  363. }
  364. }
  365. }
  366. return hasHeight && hasWidth
  367. }
  368. func isPositiveInteger(value string) bool {
  369. if value == "" {
  370. return false
  371. }
  372. if number, err := strconv.Atoi(value); err == nil {
  373. return number > 0
  374. }
  375. return false
  376. }
  377. func isSelfContainedTag(tag string) bool {
  378. switch tag {
  379. case "area", "base", "br", "col", "embed", "hr", "img", "input",
  380. "link", "meta", "param", "source", "track", "wbr":
  381. return true
  382. }
  383. return false
  384. }
  385. func isValidDataAttribute(value string) bool {
  386. for _, prefix := range dataAttributeAllowedPrefixes {
  387. if strings.HasPrefix(value, prefix) {
  388. return true
  389. }
  390. }
  391. return false
  392. }
  393. func isValidDecodingValue(value string) bool {
  394. switch value {
  395. case "sync", "async", "auto":
  396. return true
  397. }
  398. return false
  399. }
  400. func isValidFetchPriorityValue(value string) bool {
  401. switch value {
  402. case "high", "low", "auto":
  403. return true
  404. }
  405. return false
  406. }
  407. func rewriteIframeURL(link string) string {
  408. u, err := url.Parse(link)
  409. if err != nil {
  410. return link
  411. }
  412. switch strings.TrimPrefix(u.Hostname(), "www.") {
  413. case "youtube.com":
  414. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  415. if len(u.RawQuery) > 0 {
  416. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  417. }
  418. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  419. }
  420. case "player.vimeo.com":
  421. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  422. if strings.HasPrefix(u.Path, "/video/") {
  423. if len(u.RawQuery) > 0 {
  424. return link + "&dnt=1"
  425. }
  426. return link + "?dnt=1"
  427. }
  428. }
  429. return link
  430. }
  431. type mandatoryAttributesStruct struct {
  432. href bool
  433. src bool
  434. srcset bool
  435. }
  436. func trackAttributes(s *mandatoryAttributesStruct, attributeName string) {
  437. switch attributeName {
  438. case "href":
  439. s.href = true
  440. case "src":
  441. s.src = true
  442. case "srcset":
  443. s.srcset = true
  444. }
  445. }
  446. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) (string, bool) {
  447. htmlAttrs := make([]string, 0, len(attributes))
  448. // Keep track of mandatory attributes for some tags
  449. mandatoryAttributes := mandatoryAttributesStruct{false, false, false}
  450. var isAnchorLink bool
  451. var isYouTubeEmbed bool
  452. // We know the element is present, as the tag was validated in the caller of `sanitizeAttributes`
  453. allowedAttributes := allowedHTMLTagsAndAttributes[tagName]
  454. for _, attribute := range attributes {
  455. if !slices.Contains(allowedAttributes, attribute.Key) {
  456. continue
  457. }
  458. value := attribute.Val
  459. switch tagName {
  460. case "math":
  461. if attribute.Key == "xmlns" {
  462. if value != "http://www.w3.org/1998/Math/MathML" {
  463. value = "http://www.w3.org/1998/Math/MathML"
  464. }
  465. }
  466. case "img":
  467. switch attribute.Key {
  468. case "fetchpriority":
  469. if !isValidFetchPriorityValue(value) {
  470. continue
  471. }
  472. case "decoding":
  473. if !isValidDecodingValue(value) {
  474. continue
  475. }
  476. case "width", "height":
  477. if !isPositiveInteger(value) {
  478. continue
  479. }
  480. case "srcset":
  481. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  482. if value == "" {
  483. continue
  484. }
  485. }
  486. case "source":
  487. if attribute.Key == "srcset" {
  488. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  489. if value == "" {
  490. continue
  491. }
  492. }
  493. }
  494. if isExternalResourceAttribute(attribute.Key) {
  495. switch {
  496. case tagName == "iframe":
  497. iframeSourceDomain, trustedIframeDomain := findAllowedIframeSourceDomain(attribute.Val)
  498. if !trustedIframeDomain {
  499. return "", false
  500. }
  501. value = rewriteIframeURL(attribute.Val)
  502. if iframeSourceDomain == "youtube.com" || iframeSourceDomain == "youtube-nocookie.com" {
  503. isYouTubeEmbed = true
  504. }
  505. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  506. value = attribute.Val
  507. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  508. value = attribute.Val
  509. isAnchorLink = true
  510. default:
  511. if isBlockedResource(value) {
  512. return "", false
  513. }
  514. var err error
  515. value, err = urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseUrl, value)
  516. if err != nil {
  517. continue
  518. }
  519. if !hasValidURIScheme(value) {
  520. continue
  521. }
  522. // TODO use feedURL instead of baseURL twice.
  523. parsedValueUrl, _ := url.Parse(value)
  524. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  525. value = cleanedURL
  526. }
  527. }
  528. }
  529. trackAttributes(&mandatoryAttributes, attribute.Key)
  530. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  531. }
  532. if !hasRequiredAttributes(&mandatoryAttributes, tagName) {
  533. return "", false
  534. }
  535. if !isAnchorLink {
  536. switch tagName {
  537. case "a":
  538. htmlAttrs = append(htmlAttrs, `rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`)
  539. if sanitizerOptions.OpenLinksInNewTab {
  540. htmlAttrs = append(htmlAttrs, `target="_blank"`)
  541. }
  542. case "video", "audio":
  543. htmlAttrs = append(htmlAttrs, "controls")
  544. case "iframe":
  545. htmlAttrs = append(htmlAttrs, `sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`)
  546. // Note: the referrerpolicy seems to be required to avoid YouTube error 153 video player configuration error
  547. // See https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-player-api-client-identity
  548. if isYouTubeEmbed {
  549. htmlAttrs = append(htmlAttrs, `referrerpolicy="strict-origin-when-cross-origin"`)
  550. }
  551. case "img":
  552. htmlAttrs = append(htmlAttrs, `loading="lazy"`)
  553. }
  554. }
  555. return strings.Join(htmlAttrs, " "), true
  556. }
  557. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  558. candidates := ParseSrcSetAttribute(value)
  559. if len(candidates) == 0 {
  560. return ""
  561. }
  562. sanitizedCandidates := make([]*imageCandidate, 0, len(candidates))
  563. for _, imageCandidate := range candidates {
  564. absoluteURL, err := urllib.ResolveToAbsoluteURLWithParsedBaseURL(parsedBaseURL, imageCandidate.ImageURL)
  565. if err != nil {
  566. continue
  567. }
  568. if !hasValidURIScheme(absoluteURL) || isBlockedResource(absoluteURL) {
  569. continue
  570. }
  571. imageCandidate.ImageURL = absoluteURL
  572. sanitizedCandidates = append(sanitizedCandidates, imageCandidate)
  573. }
  574. return imageCandidates(sanitizedCandidates).String()
  575. }
  576. func shouldIgnoreTag(n *html.Node, tag string) bool {
  577. if isPixelTracker(tag, n.Attr) {
  578. return true
  579. }
  580. if isBlockedTag(tag) {
  581. return true
  582. }
  583. if isHidden(n) {
  584. return true
  585. }
  586. return false
  587. }