sanitizer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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]map[string]struct{}{
  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 SanitizeHTMLWithDefaultOptions(baseURL, rawHTML string) string {
  189. return SanitizeHTML(baseURL, rawHTML, &SanitizerOptions{
  190. OpenLinksInNewTab: true,
  191. })
  192. }
  193. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  194. var tagStack []string
  195. var parentTag string
  196. var blockedStack []string
  197. var buffer strings.Builder
  198. // Educated guess about how big the sanitized HTML will be,
  199. // to reduce the amount of buffer re-allocations in this function.
  200. estimatedRatio := len(rawHTML) * 3 / 4
  201. buffer.Grow(estimatedRatio)
  202. // Errors are a non-issue, so they're handled later in the function.
  203. parsedBaseUrl, _ := url.Parse(baseURL)
  204. tokenizer := html.NewTokenizer(strings.NewReader(rawHTML))
  205. for {
  206. if tokenizer.Next() == html.ErrorToken {
  207. err := tokenizer.Err()
  208. if err == io.EOF {
  209. return buffer.String()
  210. }
  211. return ""
  212. }
  213. token := tokenizer.Token()
  214. // Note: MathML elements are not fully supported by golang.org/x/net/html.
  215. // See https://github.com/golang/net/blob/master/html/atom/gen.go
  216. // and https://github.com/golang/net/blob/master/html/atom/table.go
  217. tagName := token.Data
  218. if tagName == "" {
  219. continue
  220. }
  221. switch token.Type {
  222. case html.TextToken:
  223. if len(blockedStack) > 0 {
  224. continue
  225. }
  226. // An iframe element never has fallback content.
  227. // See https://www.w3.org/TR/2010/WD-html5-20101019/the-iframe-element.html#the-iframe-element
  228. if parentTag == "iframe" {
  229. continue
  230. }
  231. buffer.WriteString(token.String())
  232. case html.StartTagToken:
  233. parentTag = tagName
  234. if isPixelTracker(tagName, token.Attr) {
  235. continue
  236. }
  237. if isBlockedTag(tagName) || slices.ContainsFunc(token.Attr, func(attr html.Attribute) bool { return attr.Key == "hidden" }) {
  238. blockedStack = append(blockedStack, tagName)
  239. continue
  240. }
  241. if len(blockedStack) == 0 && isValidTag(tagName) {
  242. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  243. if hasRequiredAttributes(tagName, attrNames) {
  244. if len(attrNames) > 0 {
  245. // Rewrite the start tag with allowed attributes.
  246. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  247. } else {
  248. // Rewrite the start tag without any attributes.
  249. buffer.WriteString("<" + tagName + ">")
  250. }
  251. tagStack = append(tagStack, tagName)
  252. }
  253. }
  254. case html.EndTagToken:
  255. if len(blockedStack) == 0 {
  256. if isValidTag(tagName) && slices.Contains(tagStack, tagName) {
  257. buffer.WriteString("</" + tagName + ">")
  258. }
  259. } else {
  260. if blockedStack[len(blockedStack)-1] == tagName {
  261. blockedStack = blockedStack[:len(blockedStack)-1]
  262. }
  263. }
  264. case html.SelfClosingTagToken:
  265. if isPixelTracker(tagName, token.Attr) {
  266. continue
  267. }
  268. if len(blockedStack) == 0 && isValidTag(tagName) {
  269. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  270. if hasRequiredAttributes(tagName, attrNames) {
  271. if len(attrNames) > 0 {
  272. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  273. } else {
  274. buffer.WriteString("<" + tagName + "/>")
  275. }
  276. }
  277. }
  278. }
  279. }
  280. }
  281. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) ([]string, string) {
  282. var htmlAttrs, attrNames []string
  283. var err error
  284. var isAnchorLink 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. if !isValidIframeSource(attribute.Val) {
  327. continue
  328. }
  329. value = rewriteIframeURL(attribute.Val)
  330. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  331. value = attribute.Val
  332. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  333. value = attribute.Val
  334. isAnchorLink = true
  335. default:
  336. value, err = absoluteURLParsedBase(parsedBaseUrl, value)
  337. if err != nil {
  338. continue
  339. }
  340. if !hasValidURIScheme(value) || isBlockedResource(value) {
  341. continue
  342. }
  343. // TODO use feedURL instead of baseURL twice.
  344. parsedValueUrl, _ := url.Parse(value)
  345. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  346. value = cleanedURL
  347. }
  348. }
  349. }
  350. attrNames = append(attrNames, attribute.Key)
  351. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  352. }
  353. if !isAnchorLink {
  354. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName, sanitizerOptions)
  355. if len(extraAttrNames) > 0 {
  356. attrNames = append(attrNames, extraAttrNames...)
  357. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  358. }
  359. }
  360. return attrNames, strings.Join(htmlAttrs, " ")
  361. }
  362. func getExtraAttributes(tagName string, sanitizerOptions *SanitizerOptions) ([]string, []string) {
  363. switch tagName {
  364. case "a":
  365. attributeNames := []string{"rel", "referrerpolicy"}
  366. htmlAttributes := []string{`rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`}
  367. if sanitizerOptions.OpenLinksInNewTab {
  368. attributeNames = append(attributeNames, "target")
  369. htmlAttributes = append(htmlAttributes, `target="_blank"`)
  370. }
  371. return attributeNames, htmlAttributes
  372. case "video", "audio":
  373. return []string{"controls"}, []string{"controls"}
  374. case "iframe":
  375. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  376. case "img":
  377. return []string{"loading"}, []string{`loading="lazy"`}
  378. default:
  379. return nil, nil
  380. }
  381. }
  382. func isValidTag(tagName string) bool {
  383. _, ok := allowedHTMLTagsAndAttributes[tagName]
  384. return ok
  385. }
  386. func isValidAttribute(tagName, attributeName string) bool {
  387. if attributes, ok := allowedHTMLTagsAndAttributes[tagName]; ok {
  388. _, allowed := attributes[attributeName]
  389. return allowed
  390. }
  391. return false
  392. }
  393. func isExternalResourceAttribute(attribute string) bool {
  394. switch attribute {
  395. case "src", "href", "poster", "cite":
  396. return true
  397. default:
  398. return false
  399. }
  400. }
  401. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  402. if tagName != "img" {
  403. return false
  404. }
  405. hasHeight := false
  406. hasWidth := false
  407. for _, attribute := range attributes {
  408. if attribute.Val == "1" || attribute.Val == "0" {
  409. switch attribute.Key {
  410. case "height":
  411. hasHeight = true
  412. case "width":
  413. hasWidth = true
  414. }
  415. }
  416. }
  417. return hasHeight && hasWidth
  418. }
  419. func hasRequiredAttributes(tagName string, attributes []string) bool {
  420. switch tagName {
  421. case "a":
  422. return slices.Contains(attributes, "href")
  423. case "iframe":
  424. return slices.Contains(attributes, "src")
  425. case "source", "img":
  426. return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset")
  427. default:
  428. return true
  429. }
  430. }
  431. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  432. func hasValidURIScheme(absoluteURL string) bool {
  433. colonIndex := strings.IndexByte(absoluteURL, ':')
  434. // Scheme must exist (colonIndex > 0). An empty scheme (e.g. ":foo") is not allowed.
  435. if colonIndex <= 0 {
  436. return false
  437. }
  438. scheme := absoluteURL[:colonIndex]
  439. _, ok := validURISchemes[strings.ToLower(scheme)]
  440. return ok
  441. }
  442. func isBlockedResource(absoluteURL string) bool {
  443. return slices.ContainsFunc(blockedResourceURLSubstrings, func(element string) bool {
  444. return strings.Contains(absoluteURL, element)
  445. })
  446. }
  447. func isValidIframeSource(iframeSourceURL string) bool {
  448. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  449. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  450. return true
  451. }
  452. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  453. return true
  454. }
  455. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  456. return true
  457. }
  458. return false
  459. }
  460. func rewriteIframeURL(link string) string {
  461. u, err := url.Parse(link)
  462. if err != nil {
  463. return link
  464. }
  465. switch strings.TrimPrefix(u.Hostname(), "www.") {
  466. case "youtube.com":
  467. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  468. if len(u.RawQuery) > 0 {
  469. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  470. }
  471. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  472. }
  473. case "player.vimeo.com":
  474. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  475. if strings.HasPrefix(u.Path, "/video/") {
  476. if len(u.RawQuery) > 0 {
  477. return link + "&dnt=1"
  478. }
  479. return link + "?dnt=1"
  480. }
  481. }
  482. return link
  483. }
  484. func isBlockedTag(tagName string) bool {
  485. switch tagName {
  486. case "noscript", "script", "style":
  487. return true
  488. }
  489. return false
  490. }
  491. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  492. imageCandidates := ParseSrcSetAttribute(value)
  493. for _, imageCandidate := range imageCandidates {
  494. if absoluteURL, err := absoluteURLParsedBase(parsedBaseURL, imageCandidate.ImageURL); err == nil {
  495. imageCandidate.ImageURL = absoluteURL
  496. }
  497. }
  498. return imageCandidates.String()
  499. }
  500. func isValidDataAttribute(value string) bool {
  501. for _, prefix := range dataAttributeAllowedPrefixes {
  502. if strings.HasPrefix(value, prefix) {
  503. return true
  504. }
  505. }
  506. return false
  507. }
  508. func isPositiveInteger(value string) bool {
  509. if value == "" {
  510. return false
  511. }
  512. if number, err := strconv.Atoi(value); err == nil {
  513. return number > 0
  514. }
  515. return false
  516. }
  517. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  518. for _, attribute := range attributes {
  519. if attribute.Key == name {
  520. number, _ := strconv.Atoi(attribute.Val)
  521. return number
  522. }
  523. }
  524. return 0
  525. }
  526. func isValidFetchPriorityValue(value string) bool {
  527. switch value {
  528. case "high", "low", "auto":
  529. return true
  530. }
  531. return false
  532. }
  533. func isValidDecodingValue(value string) bool {
  534. switch value {
  535. case "sync", "async", "auto":
  536. return true
  537. }
  538. return false
  539. }
  540. // absoluteURLParsedBase is used instead of urllib.AbsoluteURL to avoid parsing baseURL over and over.
  541. func absoluteURLParsedBase(parsedBaseURL *url.URL, input string) (string, error) {
  542. absURL, u, err := urllib.GetAbsoluteURL(input)
  543. if err != nil {
  544. return "", err
  545. }
  546. if absURL != "" {
  547. return absURL, nil
  548. }
  549. if parsedBaseURL == nil {
  550. return "", nil
  551. }
  552. return parsedBaseURL.ResolveReference(u).String(), nil
  553. }