sanitizer.go 16 KB

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