html_sanitizer.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. class HtmlSanitizer
  2. LINKABLE_URL_SCHEMES = URI.scheme_list.keys.map(&:downcase) - ['mailto'] + ['tel']
  3. PROCESSING_TIMEOUT = 20
  4. UNPROCESSABLE_HTML_MSG = 'This message cannot be displayed due to HTML processing issues. Download the raw message below and open it via an Email client if you still wish to view it.'.freeze
  5. =begin
  6. satinize html string based on whiltelist
  7. string = HtmlSanitizer.strict(string, external)
  8. =end
  9. def self.strict(string, external = false, timeout: true)
  10. Timeout.timeout(timeout ? PROCESSING_TIMEOUT : nil) do
  11. @fqdn = Setting.get('fqdn')
  12. http_type = Setting.get('http_type')
  13. web_app_url_prefix = "#{http_type}://#{@fqdn}/\#".downcase
  14. # config
  15. tags_remove_content = Rails.configuration.html_sanitizer_tags_remove_content
  16. tags_quote_content = Rails.configuration.html_sanitizer_tags_quote_content
  17. tags_whitelist = Rails.configuration.html_sanitizer_tags_whitelist
  18. attributes_whitelist = Rails.configuration.html_sanitizer_attributes_whitelist
  19. css_properties_whitelist = Rails.configuration.html_sanitizer_css_properties_whitelist
  20. css_values_blacklist = Rails.application.config.html_sanitizer_css_values_backlist
  21. # We whitelist yahoo_quoted because Yahoo Mail marks quoted email content using
  22. # <div class='yahoo_quoted'> and we rely on this class to identify quoted messages
  23. classes_whitelist = %w[js-signatureMarker yahoo_quoted]
  24. attributes_2_css = %w[width height]
  25. # remove tags with subtree
  26. scrubber_tag_remove = Loofah::Scrubber.new do |node|
  27. next if tags_remove_content.exclude?(node.name)
  28. node.remove
  29. Loofah::Scrubber::STOP
  30. end
  31. string = Loofah.fragment(string).scrub!(scrubber_tag_remove).to_s
  32. # remove tag, insert quoted content
  33. scrubber_wipe_quote_content = Loofah::Scrubber.new do |node|
  34. next if tags_quote_content.exclude?(node.name)
  35. string = html_decode(node.content)
  36. text = Nokogiri::XML::Text.new(string, node.document)
  37. node.add_next_sibling(text)
  38. node.remove
  39. Loofah::Scrubber::STOP
  40. end
  41. string = Loofah.fragment(string).scrub!(scrubber_wipe_quote_content).to_s
  42. scrubber_wipe = Loofah::Scrubber.new do |node|
  43. # replace tags, keep subtree
  44. if tags_whitelist.exclude?(node.name)
  45. node.replace node.children.to_s
  46. Loofah::Scrubber::STOP
  47. end
  48. # prepare src attribute
  49. if node['src']
  50. src = cleanup_target(CGI.unescape(node['src']))
  51. if src =~ %r{(javascript|livescript|vbscript):}i || src.downcase.start_with?('http', 'ftp', '//')
  52. node.remove
  53. Loofah::Scrubber::STOP
  54. end
  55. end
  56. # clean class / only use allowed classes
  57. if node['class']
  58. classes = node['class'].gsub(%r{\t|\n|\r}, '').split
  59. class_new = ''
  60. classes.each do |local_class|
  61. next if classes_whitelist.exclude?(local_class.to_s.strip)
  62. if class_new != ''
  63. class_new += ' '
  64. end
  65. class_new += local_class
  66. end
  67. if class_new == ''
  68. node.delete('class')
  69. else
  70. node['class'] = class_new
  71. end
  72. end
  73. # move style attributes to css attributes
  74. attributes_2_css.each do |key|
  75. next if !node[key]
  76. if node['style'].blank?
  77. node['style'] = ''
  78. else
  79. node['style'] += ';'
  80. end
  81. value = node[key]
  82. node.delete(key)
  83. next if value.blank?
  84. value += 'px' if !value.match?(%r{%|px|em}i)
  85. node['style'] += "#{key}:#{value}"
  86. end
  87. # clean style / only use allowed style properties
  88. if node['style']
  89. pears = node['style'].downcase.gsub(%r{\t|\n|\r}, '').split(';')
  90. style = ''
  91. pears.each do |local_pear|
  92. prop = local_pear.split(':')
  93. next if !prop[0]
  94. key = prop[0].strip
  95. next if css_properties_whitelist.exclude?(node.name)
  96. next if css_properties_whitelist[node.name].exclude?(key)
  97. next if css_values_blacklist[node.name]&.include?(local_pear.gsub(%r{[[:space:]]}, '').strip)
  98. style += "#{local_pear};"
  99. end
  100. node['style'] = style
  101. if style == ''
  102. node.delete('style')
  103. end
  104. end
  105. # scan for invalid link content
  106. %w[href style].each do |attribute_name|
  107. next if !node[attribute_name]
  108. href = cleanup_target(node[attribute_name])
  109. next if !href.match?(%r{(javascript|livescript|vbscript):}i)
  110. node.delete(attribute_name)
  111. end
  112. # remove attributes if not whitelisted
  113. node.each do |attribute, _value|
  114. attribute_name = attribute.downcase
  115. next if attributes_whitelist[:all].include?(attribute_name) || attributes_whitelist[node.name]&.include?(attribute_name)
  116. node.delete(attribute)
  117. end
  118. end
  119. done = true
  120. while done
  121. new_string = Loofah.fragment(string).scrub!(scrubber_wipe).to_s
  122. if string == new_string
  123. done = false
  124. end
  125. string = new_string
  126. end
  127. scrubber_link = Loofah::Scrubber.new do |node|
  128. # wrap plain-text URLs in <a> tags
  129. if node.is_a?(Nokogiri::XML::Text) && node.content.present? && node.content.include?(':') && node.ancestors.map(&:name).exclude?('a')
  130. urls = URI.extract(node.content, LINKABLE_URL_SCHEMES)
  131. .map { |u| u.sub(%r{[,.]$}, '') } # URI::extract captures trailing dots/commas
  132. .reject { |u| u.match?(%r{^[^:]+:$}) } # URI::extract will match, e.g., 'tel:'
  133. next if urls.blank?
  134. add_link(node.content, urls, node)
  135. end
  136. # prepare links
  137. if node['href']
  138. href = cleanup_target(node['href'], keep_spaces: true)
  139. href_without_spaces = href.gsub(%r{[[:space:]]}, '')
  140. if external && href_without_spaces.present? && !href_without_spaces.downcase.start_with?('mailto:') && !href_without_spaces.downcase.start_with?('//') && href_without_spaces.downcase !~ %r{^.{1,6}://.+?}
  141. node['href'] = "http://#{node['href']}"
  142. href = node['href']
  143. href_without_spaces = href.gsub(%r{[[:space:]]}, '')
  144. end
  145. next if !CGI.unescape(href_without_spaces).utf8_encode(fallback: :read_as_sanitized_binary).gsub(%r{[[:space:]]}, '').downcase.start_with?('http', 'ftp', '//')
  146. node.set_attribute('href', href)
  147. node.set_attribute('rel', 'nofollow noreferrer noopener')
  148. # do not "target=_blank" WebApp URLs (e.g. mentions)
  149. if !href.downcase.start_with?(web_app_url_prefix)
  150. node.set_attribute('target', '_blank')
  151. end
  152. end
  153. if node.name == 'a' && node['href'].blank?
  154. node.replace node.children.to_s
  155. Loofah::Scrubber::STOP
  156. end
  157. # check if href is different to text
  158. if node.name == 'a' && !url_same?(node['href'], node.text) && node['title'].blank?
  159. node['title'] = node['href']
  160. end
  161. end
  162. Loofah.fragment(string).scrub!(scrubber_link).to_s
  163. end
  164. rescue Timeout::Error
  165. Rails.logger.error "Could not process string via HtmlSanitizer.strict in #{PROCESSING_TIMEOUT} seconds. Current state: #{string}"
  166. UNPROCESSABLE_HTML_MSG
  167. end
  168. =begin
  169. cleanup html string:
  170. * remove empty nodes (p, div, span, table)
  171. * remove nodes in general (keep content - span)
  172. string = HtmlSanitizer.cleanup(string)
  173. =end
  174. def self.cleanup(string, timeout: true)
  175. Timeout.timeout(timeout ? PROCESSING_TIMEOUT : nil) do
  176. string.gsub!(%r{<[A-z]:[A-z]>}, '')
  177. string.gsub!(%r{</[A-z]:[A-z]>}, '')
  178. string.delete!("\t")
  179. # remove all new lines
  180. string.gsub!(%r{(\n\r|\r\r\n|\r\n|\n)}, "\n")
  181. # remove double multiple empty lines
  182. string.gsub!(%r{\n\n\n+}, "\n\n")
  183. string = cleanup_structure(string, 'pre')
  184. string = cleanup_structure(string)
  185. string
  186. end
  187. rescue Timeout::Error
  188. Rails.logger.error "Could not process string via HtmlSanitizer.cleanup in #{PROCESSING_TIMEOUT} seconds. Current state: #{string}"
  189. UNPROCESSABLE_HTML_MSG
  190. end
  191. def self.remove_last_empty_node(node, remove_empty_nodes, remove_empty_last_nodes)
  192. if node.children.present?
  193. if node.children.size == 1
  194. local_name = node.name
  195. child = node.children.first
  196. # replace not needed node (parent <- child)
  197. if local_name == child.name && node.attributes.present? && node.children.first.attributes.blank?
  198. local_node_child = node.children.first
  199. node.attributes.each do |k|
  200. local_node_child.set_attribute(k[0], k[1])
  201. end
  202. node.replace local_node_child.to_s
  203. Loofah::Scrubber::STOP
  204. # replace not needed node (parent replace with child node)
  205. elsif (local_name == 'span' || local_name == child.name) && node.attributes.blank?
  206. node.replace node.children.to_s
  207. Loofah::Scrubber::STOP
  208. end
  209. else
  210. # loop through nodes
  211. node.children.each do |local_node|
  212. remove_last_empty_node(local_node, remove_empty_nodes, remove_empty_last_nodes)
  213. end
  214. end
  215. # remove empty nodes
  216. elsif (remove_empty_nodes.include?(node.name) || remove_empty_last_nodes.include?(node.name)) && node.content.blank? && node.attributes.blank?
  217. node.remove
  218. Loofah::Scrubber::STOP
  219. end
  220. end
  221. def self.cleanup_structure(string, type = 'all')
  222. remove_empty_nodes = if type == 'pre'
  223. %w[span]
  224. else
  225. %w[p div span small table]
  226. end
  227. remove_empty_last_nodes = %w[b i u small table]
  228. # remove last empty nodes and empty -not needed- parrent nodes
  229. scrubber_structure = Loofah::Scrubber.new do |node|
  230. remove_last_empty_node(node, remove_empty_nodes, remove_empty_last_nodes)
  231. end
  232. done = true
  233. while done
  234. new_string = Loofah.fragment(string).scrub!(scrubber_structure).to_s
  235. if string == new_string
  236. done = false
  237. end
  238. string = new_string
  239. end
  240. scrubber_cleanup = Loofah::Scrubber.new do |node|
  241. # remove not needed new lines
  242. if node.instance_of?(Nokogiri::XML::Text)
  243. if !node.parent || (node.parent.name != 'pre' && node.parent.name != 'code') # rubocop:disable Style/SoleNestedConditional
  244. content = node.content
  245. if content
  246. if content != ' ' && content != "\n"
  247. content.gsub!(%r{[[:space:]]+}, ' ')
  248. end
  249. if node.previous
  250. if node.previous.name == 'div' || node.previous.name == 'p'
  251. content.strip!
  252. end
  253. elsif node.parent && !node.previous && (!node.next || node.next.name == 'div' || node.next.name == 'p' || node.next.name == 'br')
  254. if (node.parent.name == 'div' || node.parent.name == 'p') && content != ' ' && content != "\n"
  255. content.strip!
  256. end
  257. end
  258. node.content = content
  259. end
  260. end
  261. end
  262. end
  263. Loofah.fragment(string).scrub!(scrubber_cleanup).to_s
  264. end
  265. def self.add_link(content, urls, node)
  266. if urls.blank?
  267. text = Nokogiri::XML::Text.new(content, node.document)
  268. node.add_next_sibling(text)
  269. return
  270. end
  271. url = urls.shift
  272. if content =~ %r{^(.*)#{Regexp.quote(url)}(.*)$}mx
  273. pre = $1
  274. post = $2
  275. if url.match?(%r{^www}i)
  276. url = "http://#{url}"
  277. end
  278. a = Nokogiri::XML::Node.new 'a', node.document
  279. a['href'] = url
  280. a['rel'] = 'nofollow noreferrer noopener'
  281. a['target'] = '_blank'
  282. a.content = url
  283. if node.class != Nokogiri::XML::Text
  284. text = Nokogiri::XML::Text.new(pre, node.document)
  285. node.add_next_sibling(text).add_next_sibling(a)
  286. return if post.blank?
  287. add_link(post, urls, a)
  288. return
  289. end
  290. node.content = pre
  291. node.add_next_sibling(a)
  292. return if post.blank?
  293. add_link(post, urls, a)
  294. end
  295. true
  296. end
  297. def self.html_decode(string)
  298. string.gsub('&amp;', '&').gsub('&lt;', '<').gsub('&gt;', '>').gsub('&quot;', '"').gsub('&nbsp;', ' ')
  299. end
  300. def self.cleanup_target(string, **options)
  301. cleaned_string = string.utf8_encode(fallback: :read_as_sanitized_binary)
  302. cleaned_string = cleaned_string.gsub(%r{[[:space:]]}, '') if !options[:keep_spaces]
  303. cleaned_string = cleaned_string.strip
  304. .delete("\t\n\r\u0000")
  305. .gsub(%r{/\*.*?\*/}, '')
  306. .gsub(%r{<!--.*?-->}, '')
  307. sanitize_attachment_disposition(cleaned_string)
  308. end
  309. def self.sanitize_attachment_disposition(url)
  310. @fqdn ||= Setting.get('fqdn')
  311. uri = URI(url)
  312. if uri.host == @fqdn && uri.query.present?
  313. params = CGI.parse(uri.query || '')
  314. .tap { |p| p.merge!('disposition' => 'attachment') if p.include?('disposition') }
  315. uri.query = URI.encode_www_form(params)
  316. end
  317. uri.to_s
  318. rescue
  319. url
  320. end
  321. def self.url_same?(url_new, url_old)
  322. url_new = CGI.unescape(url_new.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(%r{[[:space:]]|\t|\n|\r}, '').strip
  323. url_old = CGI.unescape(url_old.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(%r{[[:space:]]|\t|\n|\r}, '').strip
  324. url_new = html_decode(url_new).sub('/?', '?')
  325. url_old = html_decode(url_old).sub('/?', '?')
  326. return true if url_new == url_old
  327. return true if url_old == "http://#{url_new}"
  328. return true if url_new == "http://#{url_old}"
  329. return true if url_old == "https://#{url_new}"
  330. return true if url_new == "https://#{url_old}"
  331. false
  332. end
  333. =begin
  334. reolace inline images with cid images
  335. string = HtmlSanitizer.replace_inline_images(article.body)
  336. =end
  337. def self.replace_inline_images(string, prefix = rand(999_999_999))
  338. fqdn = Setting.get('fqdn')
  339. attachments_inline = []
  340. filename_counter = 0
  341. scrubber = Loofah::Scrubber.new do |node|
  342. if node.name == 'img'
  343. if node['src'] && node['src'] =~ %r{^(data:image/(jpeg|png);base64,.+?)$}i
  344. filename_counter += 1
  345. file_attributes = StaticAssets.data_url_attributes($1)
  346. cid = "#{prefix}.#{rand(999_999_999)}@#{fqdn}"
  347. filename = cid
  348. if file_attributes[:file_extention].present?
  349. filename = "image#{filename_counter}.#{file_attributes[:file_extention]}"
  350. end
  351. attachment = {
  352. data: file_attributes[:content],
  353. filename: filename,
  354. preferences: {
  355. 'Content-Type' => file_attributes[:mime_type],
  356. 'Mime-Type' => file_attributes[:mime_type],
  357. 'Content-ID' => cid,
  358. 'Content-Disposition' => 'inline',
  359. },
  360. }
  361. attachments_inline.push attachment
  362. node['src'] = "cid:#{cid}"
  363. end
  364. Loofah::Scrubber::STOP
  365. end
  366. end
  367. [Loofah.fragment(string).scrub!(scrubber).to_s, attachments_inline]
  368. end
  369. =begin
  370. satinize style of img tags
  371. string = HtmlSanitizer.dynamic_image_size(article.body)
  372. =end
  373. def self.dynamic_image_size(string)
  374. scrubber = Loofah::Scrubber.new do |node|
  375. if node.name == 'img'
  376. if node['src']
  377. style = 'max-width:100%;'
  378. if node['style']
  379. pears = node['style'].downcase.gsub(%r{\t|\n|\r}, '').split(';')
  380. pears.each do |local_pear|
  381. prop = local_pear.split(':')
  382. next if !prop[0]
  383. key = prop[0].strip
  384. if key == 'height'
  385. key = 'max-height'
  386. end
  387. style += "#{key}:#{prop[1]};"
  388. end
  389. end
  390. node['style'] = style
  391. end
  392. Loofah::Scrubber::STOP
  393. end
  394. end
  395. Loofah.fragment(string).scrub!(scrubber).to_s
  396. end
  397. private_class_method :cleanup_target
  398. private_class_method :sanitize_attachment_disposition
  399. private_class_method :add_link
  400. private_class_method :url_same?
  401. private_class_method :html_decode
  402. end