html_sanitizer.rb 15 KB

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