sanitizer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. validURISchemes = map[string]struct{}{
  133. "apt": {},
  134. "bitcoin": {},
  135. "callto": {},
  136. "dav": {},
  137. "davs": {},
  138. "ed2k": {},
  139. "facetime": {},
  140. "feed": {},
  141. "ftp": {},
  142. "geo": {},
  143. "git": {},
  144. "gopher": {},
  145. "http": {},
  146. "https": {},
  147. "irc": {},
  148. "irc6": {},
  149. "ircs": {},
  150. "itms-apps": {},
  151. "itms": {},
  152. "magnet": {},
  153. "mailto": {},
  154. "news": {},
  155. "nntp": {},
  156. "rtmp": {},
  157. "sftp": {},
  158. "sip": {},
  159. "sips": {},
  160. "skype": {},
  161. "spotify": {},
  162. "ssh": {},
  163. "steam": {},
  164. "svn": {},
  165. "svn+ssh": {},
  166. "tel": {},
  167. "webcal": {},
  168. "xmpp": {},
  169. // iOS Apps
  170. "opener": {}, // https://www.opener.link
  171. "hack": {}, // https://apps.apple.com/it/app/hack-for-hacker-news-reader/id1464477788?l=en-GB
  172. }
  173. dataAttributeAllowedPrefixes = []string{
  174. "data:image/avif",
  175. "data:image/apng",
  176. "data:image/png",
  177. "data:image/svg",
  178. "data:image/svg+xml",
  179. "data:image/jpg",
  180. "data:image/jpeg",
  181. "data:image/gif",
  182. "data:image/webp",
  183. }
  184. )
  185. type SanitizerOptions struct {
  186. OpenLinksInNewTab bool
  187. }
  188. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  189. var tagStack []string
  190. var parentTag string
  191. var blockedStack []string
  192. var buffer strings.Builder
  193. // Educated guess about how big the sanitized HTML will be,
  194. // to reduce the amount of buffer re-allocations in this function.
  195. estimatedRatio := len(rawHTML) * 3 / 4
  196. buffer.Grow(estimatedRatio)
  197. // Errors are a non-issue, so they're handled later in the function.
  198. parsedBaseUrl, _ := url.Parse(baseURL)
  199. tokenizer := html.NewTokenizer(strings.NewReader(rawHTML))
  200. for {
  201. if tokenizer.Next() == html.ErrorToken {
  202. err := tokenizer.Err()
  203. if err == io.EOF {
  204. return buffer.String()
  205. }
  206. return ""
  207. }
  208. token := tokenizer.Token()
  209. // Note: MathML elements are not fully supported by golang.org/x/net/html.
  210. // See https://github.com/golang/net/blob/master/html/atom/gen.go
  211. // and https://github.com/golang/net/blob/master/html/atom/table.go
  212. tagName := token.Data
  213. if tagName == "" {
  214. continue
  215. }
  216. switch token.Type {
  217. case html.TextToken:
  218. if len(blockedStack) > 0 {
  219. continue
  220. }
  221. // An iframe element never has fallback content.
  222. // See https://www.w3.org/TR/2010/WD-html5-20101019/the-iframe-element.html#the-iframe-element
  223. if parentTag == "iframe" {
  224. continue
  225. }
  226. buffer.WriteString(token.String())
  227. case html.StartTagToken:
  228. parentTag = tagName
  229. if isPixelTracker(tagName, token.Attr) {
  230. continue
  231. }
  232. if isBlockedTag(tagName) || slices.ContainsFunc(token.Attr, func(attr html.Attribute) bool { return attr.Key == "hidden" }) {
  233. blockedStack = append(blockedStack, tagName)
  234. continue
  235. }
  236. if len(blockedStack) == 0 && isValidTag(tagName) {
  237. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  238. if hasRequiredAttributes(tagName, attrNames) {
  239. if len(attrNames) > 0 {
  240. // Rewrite the start tag with allowed attributes.
  241. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  242. } else {
  243. // Rewrite the start tag without any attributes.
  244. buffer.WriteString("<" + tagName + ">")
  245. }
  246. tagStack = append(tagStack, tagName)
  247. }
  248. }
  249. case html.EndTagToken:
  250. if len(blockedStack) == 0 {
  251. if isValidTag(tagName) && slices.Contains(tagStack, tagName) {
  252. buffer.WriteString("</" + tagName + ">")
  253. }
  254. } else {
  255. if blockedStack[len(blockedStack)-1] == tagName {
  256. blockedStack = blockedStack[:len(blockedStack)-1]
  257. }
  258. }
  259. case html.SelfClosingTagToken:
  260. if isPixelTracker(tagName, token.Attr) {
  261. continue
  262. }
  263. if len(blockedStack) == 0 && isValidTag(tagName) {
  264. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  265. if hasRequiredAttributes(tagName, attrNames) {
  266. if len(attrNames) > 0 {
  267. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  268. } else {
  269. buffer.WriteString("<" + tagName + "/>")
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) ([]string, string) {
  277. var htmlAttrs, attrNames []string
  278. var err error
  279. var isAnchorLink bool
  280. for _, attribute := range attributes {
  281. if !isValidAttribute(tagName, attribute.Key) {
  282. continue
  283. }
  284. value := attribute.Val
  285. switch tagName {
  286. case "math":
  287. if attribute.Key == "xmlns" {
  288. if value != "http://www.w3.org/1998/Math/MathML" {
  289. value = "http://www.w3.org/1998/Math/MathML"
  290. }
  291. }
  292. case "img":
  293. switch attribute.Key {
  294. case "fetchpriority":
  295. if !isValidFetchPriorityValue(value) {
  296. continue
  297. }
  298. case "decoding":
  299. if !isValidDecodingValue(value) {
  300. continue
  301. }
  302. case "width", "height":
  303. if !isPositiveInteger(value) {
  304. continue
  305. }
  306. // Discard width and height attributes when width is larger than Miniflux layout (750px)
  307. if imgWidth := getIntegerAttributeValue("width", attributes); imgWidth > 750 {
  308. continue
  309. }
  310. case "srcset":
  311. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  312. }
  313. case "source":
  314. if attribute.Key == "srcset" {
  315. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  316. }
  317. }
  318. if isExternalResourceAttribute(attribute.Key) {
  319. switch {
  320. case tagName == "iframe":
  321. if !isValidIframeSource(attribute.Val) {
  322. continue
  323. }
  324. value = rewriteIframeURL(attribute.Val)
  325. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  326. value = attribute.Val
  327. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  328. value = attribute.Val
  329. isAnchorLink = true
  330. default:
  331. value, err = absoluteURLParsedBase(parsedBaseUrl, value)
  332. if err != nil {
  333. continue
  334. }
  335. if !hasValidURIScheme(value) || isBlockedResource(value) {
  336. continue
  337. }
  338. // TODO use feedURL instead of baseURL twice.
  339. parsedValueUrl, _ := url.Parse(value)
  340. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  341. value = cleanedURL
  342. }
  343. }
  344. }
  345. attrNames = append(attrNames, attribute.Key)
  346. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  347. }
  348. if !isAnchorLink {
  349. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName, sanitizerOptions)
  350. if len(extraAttrNames) > 0 {
  351. attrNames = append(attrNames, extraAttrNames...)
  352. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  353. }
  354. }
  355. return attrNames, strings.Join(htmlAttrs, " ")
  356. }
  357. func getExtraAttributes(tagName string, sanitizerOptions *SanitizerOptions) ([]string, []string) {
  358. switch tagName {
  359. case "a":
  360. attributeNames := []string{"rel", "referrerpolicy"}
  361. htmlAttributes := []string{`rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`}
  362. if sanitizerOptions.OpenLinksInNewTab {
  363. attributeNames = append(attributeNames, "target")
  364. htmlAttributes = append(htmlAttributes, `target="_blank"`)
  365. }
  366. return attributeNames, htmlAttributes
  367. case "video", "audio":
  368. return []string{"controls"}, []string{"controls"}
  369. case "iframe":
  370. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  371. case "img":
  372. return []string{"loading"}, []string{`loading="lazy"`}
  373. default:
  374. return nil, nil
  375. }
  376. }
  377. func isValidTag(tagName string) bool {
  378. _, ok := allowedHTMLTagsAndAttributes[tagName]
  379. return ok
  380. }
  381. func isValidAttribute(tagName, attributeName string) bool {
  382. if attributes, ok := allowedHTMLTagsAndAttributes[tagName]; ok {
  383. return slices.Contains(attributes, attributeName)
  384. }
  385. return false
  386. }
  387. func isExternalResourceAttribute(attribute string) bool {
  388. switch attribute {
  389. case "src", "href", "poster", "cite":
  390. return true
  391. default:
  392. return false
  393. }
  394. }
  395. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  396. if tagName != "img" {
  397. return false
  398. }
  399. hasHeight := false
  400. hasWidth := false
  401. for _, attribute := range attributes {
  402. if attribute.Val == "1" || attribute.Val == "0" {
  403. switch attribute.Key {
  404. case "height":
  405. hasHeight = true
  406. case "width":
  407. hasWidth = true
  408. }
  409. }
  410. }
  411. return hasHeight && hasWidth
  412. }
  413. func hasRequiredAttributes(tagName string, attributes []string) bool {
  414. switch tagName {
  415. case "a":
  416. return slices.Contains(attributes, "href")
  417. case "iframe":
  418. return slices.Contains(attributes, "src")
  419. case "source", "img":
  420. return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset")
  421. default:
  422. return true
  423. }
  424. }
  425. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  426. func hasValidURIScheme(absoluteURL string) bool {
  427. colonIndex := strings.IndexByte(absoluteURL, ':')
  428. // Scheme must exist (colonIndex > 0). An empty scheme (e.g. ":foo") is not allowed.
  429. if colonIndex <= 0 {
  430. return false
  431. }
  432. scheme := absoluteURL[:colonIndex]
  433. _, ok := validURISchemes[strings.ToLower(scheme)]
  434. return ok
  435. }
  436. func isBlockedResource(absoluteURL string) bool {
  437. return slices.ContainsFunc(blockedResourceURLSubstrings, func(element string) bool {
  438. return strings.Contains(absoluteURL, element)
  439. })
  440. }
  441. func isValidIframeSource(iframeSourceURL string) bool {
  442. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  443. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  444. return true
  445. }
  446. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  447. return true
  448. }
  449. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  450. return true
  451. }
  452. return false
  453. }
  454. func rewriteIframeURL(link string) string {
  455. u, err := url.Parse(link)
  456. if err != nil {
  457. return link
  458. }
  459. switch strings.TrimPrefix(u.Hostname(), "www.") {
  460. case "youtube.com":
  461. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  462. if len(u.RawQuery) > 0 {
  463. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  464. }
  465. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  466. }
  467. case "player.vimeo.com":
  468. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  469. if strings.HasPrefix(u.Path, "/video/") {
  470. if len(u.RawQuery) > 0 {
  471. return link + "&dnt=1"
  472. }
  473. return link + "?dnt=1"
  474. }
  475. }
  476. return link
  477. }
  478. func isBlockedTag(tagName string) bool {
  479. switch tagName {
  480. case "noscript", "script", "style":
  481. return true
  482. }
  483. return false
  484. }
  485. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  486. imageCandidates := ParseSrcSetAttribute(value)
  487. for _, imageCandidate := range imageCandidates {
  488. if absoluteURL, err := absoluteURLParsedBase(parsedBaseURL, imageCandidate.ImageURL); err == nil {
  489. imageCandidate.ImageURL = absoluteURL
  490. }
  491. }
  492. return imageCandidates.String()
  493. }
  494. func isValidDataAttribute(value string) bool {
  495. for _, prefix := range dataAttributeAllowedPrefixes {
  496. if strings.HasPrefix(value, prefix) {
  497. return true
  498. }
  499. }
  500. return false
  501. }
  502. func isPositiveInteger(value string) bool {
  503. if value == "" {
  504. return false
  505. }
  506. if number, err := strconv.Atoi(value); err == nil {
  507. return number > 0
  508. }
  509. return false
  510. }
  511. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  512. for _, attribute := range attributes {
  513. if attribute.Key == name {
  514. number, _ := strconv.Atoi(attribute.Val)
  515. return number
  516. }
  517. }
  518. return 0
  519. }
  520. func isValidFetchPriorityValue(value string) bool {
  521. switch value {
  522. case "high", "low", "auto":
  523. return true
  524. }
  525. return false
  526. }
  527. func isValidDecodingValue(value string) bool {
  528. switch value {
  529. case "sync", "async", "auto":
  530. return true
  531. }
  532. return false
  533. }
  534. // absoluteURLParsedBase is used instead of urllib.AbsoluteURL to avoid parsing baseURL over and over.
  535. func absoluteURLParsedBase(parsedBaseURL *url.URL, input string) (string, error) {
  536. absURL, u, err := urllib.GetAbsoluteURL(input)
  537. if err != nil {
  538. return "", err
  539. }
  540. if absURL != "" {
  541. return absURL, nil
  542. }
  543. if parsedBaseURL == nil {
  544. return "", nil
  545. }
  546. return parsedBaseURL.ResolveReference(u).String(), nil
  547. }