html_sanitizer.rb 16 KB

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