Class: Sanitize

Inherits:
Object
  • Object
show all
Defined in:
lib/sanitize/config.rb,
lib/sanitize.rb,
lib/sanitize/config/basic.rb,
lib/sanitize/config/relaxed.rb,
lib/sanitize/config/restricted.rb

Overview

– Copyright © 2009 Ryan Grove <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++

Defined Under Namespace

Modules: Config

Constant Summary collapse

ENTITY_MAP =

Characters that should be replaced with entities in text nodes.

{
  '<' => '&lt;',
  '>' => '&gt;',
  '"' => '&quot;',
  "'" => '&#39;'
}
REGEX_AMPERSAND =

Matches an unencoded ampersand that is not part of a valid character entity reference.

/&(?!(?:[a-z]+[0-9]{0,2}|#[0-9]+|#x[0-9a-f]+);)/i
REGEX_PROTOCOL =

Matches an attribute value that could be treated by a browser as a URL with a protocol prefix, such as “http:” or “javascript:”. Any string of zero or more characters followed by a colon is considered a match, even if the colon is encoded as an entity and even if it’s an incomplete entity (which IE6 and Opera will still parse).

/^([A-Za-z0-9\+\-\.\&\;\#\s]*?)(?:\:|&#0*58|&#x0*3a)/i

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Sanitize

Returns a new Sanitize object initialized with the settings in config.



63
64
65
# File 'lib/sanitize.rb', line 63

def initialize(config = {})
  @config = Config::DEFAULT.merge(config)
end

Class Method Details

.clean(html, config = {}) ⇒ Object

Returns a sanitized copy of html, using the settings in config if specified.



162
163
164
165
# File 'lib/sanitize.rb', line 162

def clean(html, config = {})
  sanitize = Sanitize.new(config)
  sanitize.clean(html)
end

.clean!(html, config = {}) ⇒ Object

Performs Sanitize#clean in place, returning html, or nil if no changes were made.



169
170
171
172
# File 'lib/sanitize.rb', line 169

def clean!(html, config = {})
  sanitize = Sanitize.new(config)
  sanitize.clean!(html)
end

.encode_html(html) ⇒ Object

Encodes special HTML characters (<, >, “, ‘, and &) in html as entity references and returns the encoded string.



176
177
178
179
180
181
182
183
184
# File 'lib/sanitize.rb', line 176

def encode_html(html)
  str = html.dup

  # Encode special chars.
  ENTITY_MAP.each {|char, entity| str.gsub!(char, entity) }

  # Convert unencoded ampersands to entity references.
  str.gsub(REGEX_AMPERSAND, '&amp;')
end

Instance Method Details

#clean(html) ⇒ Object

Returns a sanitized copy of html.



68
69
70
71
# File 'lib/sanitize.rb', line 68

def clean(html)
  dupe = html.dup
  clean!(dupe) || dupe
end

#clean!(html) ⇒ Object

Performs clean in place, returning html, or nil if no changes were made.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/sanitize.rb', line 75

def clean!(html)
  fragment = Hpricot(html)

  fragment.search('*') do |node|
    if node.bogusetag? || node.doctype? || node.procins? || node.xmldecl?
      node.parent.replace_child(node, '')
      next
    end

    if node.comment?
      node.parent.replace_child(node, '') unless @config[:allow_comments]
    elsif node.elem?
      name = node.name.to_s.downcase

      # Delete any element that isn't in the whitelist.
      unless @config[:elements].include?(name)
        node.parent.replace_child(node, node.children || '')
        next
      end

      node.raw_attributes ||= {}

      attr_whitelist = ((@config[:attributes][name] || []) +
          (@config[:attributes][:all] || [])).uniq

      if attr_whitelist.empty?
        # Delete all attributes from elements with no whitelisted
        # attributes.
        node.raw_attributes = {}
      else
        # Delete any attribute that isn't in the whitelist for this element.
        node.raw_attributes.delete_if do |key, value|
          !attr_whitelist.include?(key.to_s.downcase)
        end

        # Delete remaining attributes that use unacceptable protocols.
        if @config[:protocols].has_key?(name)
          protocol = @config[:protocols][name]

          node.raw_attributes.delete_if do |key, value|
            key = key.to_s.downcase
            next false unless protocol.has_key?(key)
            next true if value.nil?

            if value.to_s.downcase =~ REGEX_PROTOCOL
              !protocol[key].include?($1.downcase)
            else
              !protocol[key].include?(:relative)
            end
          end
        end
      end

      # Add required attributes.
      if @config[:add_attributes].has_key?(name)
        node.raw_attributes.merge!(@config[:add_attributes][name])
      end

      unless @config[:skip_encoding]
        # Escape special chars in attribute values.
        node.raw_attributes.each do |key, value|
          node.raw_attributes[key] = Sanitize.encode_html(value)
        end
      end
    end
  end

  # Make one last pass through the fragment and encode all special HTML chars
  # as entities. This eliminates certain types of maliciously-malformed nested
  # tags.
  unless @config[:skip_encoding]
    fragment.search('*') do |node|
      node.swap(Sanitize.encode_html(node.to_original_html)) if node.text?
    end
  end

  result = fragment.to_s
  return result == html ? nil : html[0, html.length] = result
end