html_sanitizer.rb 16 KB

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