html_sanitizer.rb 16 KB

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