html_sanitizer.rb 16 KB

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