sanitizer.go 16 KB

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