html_sanitizer.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. class HtmlSanitizer
  2. LINKABLE_URL_SCHEMES = URI.scheme_list.keys.map(&:downcase) - ['mailto'] + ['tel']
  3. =begin
  4. satinize html string based on whiltelist
  5. string = HtmlSanitizer.strict(string, external)
  6. =end
  7. def self.strict(string, external = false)
  8. # config
  9. tags_remove_content = Rails.configuration.html_sanitizer_tags_remove_content
  10. tags_quote_content = Rails.configuration.html_sanitizer_tags_quote_content
  11. tags_whitelist = Rails.configuration.html_sanitizer_tags_whitelist
  12. attributes_whitelist = Rails.configuration.html_sanitizer_attributes_whitelist
  13. css_properties_whitelist = Rails.configuration.html_sanitizer_css_properties_whitelist
  14. css_values_blacklist = Rails.application.config.html_sanitizer_css_values_backlist
  15. # We whitelist yahoo_quoted because Yahoo Mail marks quoted email content using
  16. # <div class='yahoo_quoted'> and we rely on this class to identify quoted messages
  17. classes_whitelist = ['js-signatureMarker', 'yahoo_quoted']
  18. attributes_2_css = %w[width height]
  19. # remove html comments
  20. string.gsub!(/<!--.+?-->/m, '')
  21. scrubber_link = Loofah::Scrubber.new do |node|
  22. # wrap plain-text URLs in <a> tags
  23. if node.is_a?(Nokogiri::XML::Text) && node.content.present? && node.content.include?(':') && node.ancestors.map(&:name).exclude?('a')
  24. urls = URI.extract(node.content, LINKABLE_URL_SCHEMES)
  25. .map { |u| u.sub(/[,.]$/, '') } # URI::extract captures trailing dots/commas
  26. .reject { |u| u.match?(/^[^:]+:$/) } # URI::extract will match, e.g., 'tel:'
  27. next if urls.blank?
  28. add_link(node.content, urls, node)
  29. end
  30. # prepare links
  31. if node['href']
  32. href = cleanup_target(node['href'], keep_spaces: true)
  33. href_without_spaces = href.gsub(/[[:space:]]/, '')
  34. if external && href_without_spaces.present? && !href_without_spaces.downcase.start_with?('//') && href_without_spaces.downcase !~ %r{^.{1,6}://.+?}
  35. node['href'] = "http://#{node['href']}"
  36. href = node['href']
  37. href_without_spaces = href.gsub(/[[:space:]]/, '')
  38. end
  39. next if !href_without_spaces.downcase.start_with?('http', 'ftp', '//')
  40. node.set_attribute('href', href)
  41. node.set_attribute('rel', 'nofollow noreferrer noopener')
  42. node.set_attribute('target', '_blank')
  43. end
  44. if node.name == 'a' && node['href'].blank?
  45. node.replace node.children.to_s
  46. Loofah::Scrubber::STOP
  47. end
  48. # check if href is different to text
  49. if node.name == 'a' && !url_same?(node['href'], node.text)
  50. if node['title'].blank?
  51. node['title'] = node['href']
  52. end
  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.include?(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.include?(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['class'] = class_new
  95. else
  96. node.delete('class')
  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.include?(node.name)
  122. next if !css_properties_whitelist[node.name].include?(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 !~ /(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. # remove mailto links
  145. if node['href']
  146. href = cleanup_target(node['href'])
  147. if href =~ /mailto:(.*)$/i
  148. text = Nokogiri::XML::Text.new($1, node.document)
  149. node.add_next_sibling(text)
  150. node.remove
  151. Loofah::Scrubber::STOP
  152. end
  153. end
  154. end
  155. new_string = ''
  156. done = true
  157. while done
  158. new_string = Loofah.fragment(string).scrub!(scrubber_wipe).to_s
  159. if string == new_string
  160. done = false
  161. end
  162. string = new_string
  163. end
  164. Loofah.fragment(string).scrub!(scrubber_link).to_s
  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)
  173. string.gsub!(/<[A-z]:[A-z]>/, '')
  174. string.gsub!(%r{</[A-z]:[A-z]>}, '')
  175. string.delete!("\t")
  176. # remove all new lines
  177. string.gsub!(/(\n\r|\r\r\n|\r\n|\n)/, "\n")
  178. # remove double multiple empty lines
  179. string.gsub!(/\n\n\n+/, "\n\n")
  180. string = cleanup_structure(string, 'pre')
  181. string = cleanup_replace_tags(string)
  182. string = cleanup_structure(string)
  183. string
  184. end
  185. def self.cleanup_replace_tags(string)
  186. #return string
  187. tags_backlist = %w[span center]
  188. scrubber = Loofah::Scrubber.new do |node|
  189. next if !tags_backlist.include?(node.name)
  190. hit = false
  191. local_node = nil
  192. (1..5).each do |_count|
  193. local_node = if local_node
  194. local_node.parent
  195. else
  196. node.parent
  197. end
  198. break if !local_node
  199. next if local_node.name != 'td'
  200. hit = true
  201. end
  202. next if hit && node.keys.count.positive?
  203. node.replace cleanup_replace_tags(node.children.to_s)
  204. Loofah::Scrubber::STOP
  205. end
  206. Loofah.fragment(string).scrub!(scrubber).to_s
  207. end
  208. def self.cleanup_structure(string, type = 'all')
  209. remove_empty_nodes = if type == 'pre'
  210. %w[span]
  211. else
  212. %w[p div span small table]
  213. end
  214. remove_empty_last_nodes = %w[b i u small table]
  215. # remove last empty nodes and empty -not needed- parrent nodes
  216. scrubber_structure = Loofah::Scrubber.new do |node|
  217. if remove_empty_last_nodes.include?(node.name) && node.children.size.zero?
  218. node.remove
  219. Loofah::Scrubber::STOP
  220. end
  221. # remove empty childs
  222. if node.content.blank? && remove_empty_nodes.include?(node.name) && node.children.size == 1 && remove_empty_nodes.include?(node.children.first.name)
  223. node.replace node.children.to_s
  224. Loofah::Scrubber::STOP
  225. end
  226. # remove empty childs
  227. 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
  228. node.replace node.children.to_s
  229. Loofah::Scrubber::STOP
  230. end
  231. # remove node if empty and parent was already a remove node
  232. if node.content.blank? && remove_empty_nodes.include?(node.name) && node.parent && node.children.size.zero? && remove_empty_nodes.include?(node.parent.name)
  233. node.remove
  234. Loofah::Scrubber::STOP
  235. end
  236. end
  237. new_string = ''
  238. done = true
  239. while done
  240. new_string = Loofah.fragment(string).scrub!(scrubber_structure).to_s
  241. if string == new_string
  242. done = false
  243. end
  244. string = new_string
  245. end
  246. scrubber_cleanup = Loofah::Scrubber.new do |node|
  247. # remove mailto links
  248. if node['href']
  249. href = cleanup_target(node['href'])
  250. if href =~ /mailto:(.*)$/i
  251. text = Nokogiri::XML::Text.new($1, node.document)
  252. node.add_next_sibling(text)
  253. node.remove
  254. Loofah::Scrubber::STOP
  255. end
  256. end
  257. # remove not needed new lines
  258. if node.class == Nokogiri::XML::Text
  259. if !node.parent || (node.parent.name != 'pre' && node.parent.name != 'code')
  260. content = node.content
  261. if content
  262. if content != ' ' && content != "\n"
  263. content.gsub!(/[[:space:]]+/, ' ')
  264. end
  265. if node.previous
  266. if node.previous.name == 'div' || node.previous.name == 'p'
  267. content.strip!
  268. end
  269. elsif node.parent && !node.previous && (!node.next || node.next.name == 'div' || node.next.name == 'p' || node.next.name == 'br')
  270. if (node.parent.name == 'div' || node.parent.name == 'p') && content != ' ' && content != "\n"
  271. content.strip!
  272. end
  273. end
  274. node.content = content
  275. end
  276. end
  277. end
  278. end
  279. Loofah.fragment(string).scrub!(scrubber_cleanup).to_s
  280. end
  281. def self.add_link(content, urls, node)
  282. if urls.blank?
  283. text = Nokogiri::XML::Text.new(content, node.document)
  284. node.add_next_sibling(text)
  285. return
  286. end
  287. url = urls.shift
  288. if content =~ /^(.*)#{Regexp.quote(url)}(.*)$/mx
  289. pre = $1
  290. post = $2
  291. if url.match?(/^www/i)
  292. url = "http://#{url}"
  293. end
  294. a = Nokogiri::XML::Node.new 'a', node.document
  295. a['href'] = url
  296. a['rel'] = 'nofollow noreferrer noopener'
  297. a['target'] = '_blank'
  298. a.content = url
  299. if node.class != Nokogiri::XML::Text
  300. text = Nokogiri::XML::Text.new(pre, node.document)
  301. node.add_next_sibling(text).add_next_sibling(a)
  302. return if post.blank?
  303. add_link(post, urls, a)
  304. return
  305. end
  306. node.content = pre
  307. node.add_next_sibling(a)
  308. return if post.blank?
  309. add_link(post, urls, a)
  310. end
  311. true
  312. end
  313. def self.html_decode(string)
  314. string.gsub('&amp;', '&').gsub('&lt;', '<').gsub('&gt;', '>').gsub('&quot;', '"').gsub('&nbsp;', ' ')
  315. end
  316. def self.cleanup_target(string, **options)
  317. cleaned_string = CGI.unescape(string).utf8_encode(fallback: :read_as_sanitized_binary)
  318. cleaned_string = cleaned_string.gsub(/[[:space:]]/, '') if !options[:keep_spaces]
  319. cleaned_string = cleaned_string.strip
  320. .delete("\t\n\r\u0000")
  321. .gsub(%r{/\*.*?\*/}, '')
  322. .gsub(/<!--.*?-->/, '')
  323. .gsub(/\[.+?\]/, '')
  324. sanitize_attachment_disposition(cleaned_string)
  325. end
  326. def self.sanitize_attachment_disposition(url)
  327. uri = URI(url)
  328. if uri.host == Setting.get('fqdn') && uri.query.present?
  329. params = CGI.parse(uri.query || '')
  330. .tap { |p| p.merge!('disposition' => 'attachment') if p.include?('disposition') }
  331. uri.query = URI.encode_www_form(params)
  332. end
  333. uri.to_s
  334. rescue
  335. url
  336. end
  337. def self.url_same?(url_new, url_old)
  338. url_new = CGI.unescape(url_new.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip
  339. url_old = CGI.unescape(url_old.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip
  340. url_new = html_decode(url_new).sub('/?', '?')
  341. url_old = html_decode(url_old).sub('/?', '?')
  342. return true if url_new == url_old
  343. return true if url_old == "http://#{url_new}"
  344. return true if url_new == "http://#{url_old}"
  345. return true if url_old == "https://#{url_new}"
  346. return true if url_new == "https://#{url_old}"
  347. false
  348. end
  349. =begin
  350. reolace inline images with cid images
  351. string = HtmlSanitizer.replace_inline_images(article.body)
  352. =end
  353. def self.replace_inline_images(string, prefix = rand(999_999_999))
  354. attachments_inline = []
  355. filename_counter = 0
  356. scrubber = Loofah::Scrubber.new do |node|
  357. if node.name == 'img'
  358. if node['src'] && node['src'] =~ %r{^(data:image/(jpeg|png);base64,.+?)$}i
  359. filename_counter += 1
  360. file_attributes = StaticAssets.data_url_attributes($1)
  361. cid = "#{prefix}.#{rand(999_999_999)}@#{Setting.get('fqdn')}"
  362. filename = cid
  363. if file_attributes[:file_extention].present?
  364. filename = "image#{filename_counter}.#{file_attributes[:file_extention]}"
  365. end
  366. attachment = {
  367. data: file_attributes[:content],
  368. filename: filename,
  369. preferences: {
  370. 'Content-Type' => file_attributes[:mime_type],
  371. 'Mime-Type' => file_attributes[:mime_type],
  372. 'Content-ID' => cid,
  373. 'Content-Disposition' => 'inline',
  374. },
  375. }
  376. attachments_inline.push attachment
  377. node['src'] = "cid:#{cid}"
  378. end
  379. Loofah::Scrubber::STOP
  380. end
  381. end
  382. [Loofah.fragment(string).scrub!(scrubber).to_s, attachments_inline]
  383. end
  384. =begin
  385. satinize style of img tags
  386. string = HtmlSanitizer.dynamic_image_size(article.body)
  387. =end
  388. def self.dynamic_image_size(string)
  389. scrubber = Loofah::Scrubber.new do |node|
  390. if node.name == 'img'
  391. if node['src']
  392. style = 'max-width:100%;'
  393. if node['style']
  394. pears = node['style'].downcase.gsub(/\t|\n|\r/, '').split(';')
  395. pears.each do |local_pear|
  396. prop = local_pear.split(':')
  397. next if !prop[0]
  398. key = prop[0].strip
  399. if key == 'height'
  400. key = 'max-height'
  401. end
  402. style += "#{key}:#{prop[1]};"
  403. end
  404. end
  405. node['style'] = style
  406. end
  407. Loofah::Scrubber::STOP
  408. end
  409. end
  410. Loofah.fragment(string).scrub!(scrubber).to_s
  411. end
  412. private_class_method :cleanup_target
  413. private_class_method :sanitize_attachment_disposition
  414. private_class_method :add_link
  415. private_class_method :url_same?
  416. private_class_method :html_decode
  417. end