CVE-2018-3740 (published 2018-03-30T19:29Z)

A specially crafted HTML fragment can cause Sanitize gem for Ruby to allow non-whitelisted attributes to be used on a whitelisted HTML element.

Severity: MEDIUM
CVSS v2 base score: 5.0 (AV:N/AC:L/Au:N/C:N/I:P/A:N)
CVSS v3 base score: 7.5, HIGH (CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/rgrove/sanitize
commit_details: repo_url: https://github.com/rgrove/sanitize
author: Ryan Grove
author_date: 2018-03-19 19:17:59-07:00
msg: fix: Prevent code injection due to improper escaping in libxml2 >= 2.9.2

When Sanitize <= 4.6.2 is used in combination with libxml2 >= 2.9.2, a
specially crafted HTML fragment can cause libxml2 to generate improperly
escaped output, allowing non-whitelisted attributes to be used on
whitelisted elements.

Sanitize now performs additional escaping on affected attributes to
prevent this.

Many thanks to the Shopify Application Security Team for responsibly
reporting this issue.

Fixes #176
repository: repo_url: https://github.com/rgrove/sanitize
repo_name: rgrove/sanitize
description: Ruby HTML and CSS sanitizer.
repo_language: HTML
owner: rgrove
file_changes: filename: clean_element.rb
change_type: ModificationType.MODIFY
diff: @@ -18,6 +18,31 @@ class Sanitize; module Transformers; class CleanElement
   # http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data-with-the-data-*-attributes
   REGEX_DATA_ATTR = /\Adata-(?!xml)[a-z_][\w.\u00E0-\u00F6\u00F8-\u017F\u01DD-\u02AF-]*\z/u
 
+  # Attributes that need additional escaping on `<a>` elements due to unsafe
+  # libxml2 behavior.
+  UNSAFE_LIBXML_ATTRS_A = Set.new(%w[
+    name
+  ])
+
+  # Attributes that need additional escaping on all elements due to unsafe
+  # libxml2 behavior.
+  UNSAFE_LIBXML_ATTRS_GLOBAL = Set.new(%w[
+    action
+    href
+    src
+  ])
+
+  # Mapping of original characters to escape sequences for characters that
+  # should be escaped in attributes affected by unsafe libxml2 behavior.
+  UNSAFE_LIBXML_ESCAPE_CHARS = {
+    ' ' => '%20',
+    '"' => '%22'
+  }
+
+  # Regex that matches any single character that needs to be escaped in
+  # attributes affected by unsafe libxml2 behavior.
+  UNSAFE_LIBXML_ESCAPE_REGEX = /[ "]/
+
   def initialize(config)
     @add_attributes          = config[:add_attributes]
     @attributes              = config[:attributes].dup
@@ -92,31 +117,61 @@ class Sanitize; module Transformers; class CleanElement
       node.attribute_nodes.each do |attr|
         attr_name = attr.name.downcase
 
-        if attr_whitelist.include?(attr_name)
-          # The attribute is whitelisted.
+        unless attr_whitelist.include?(attr_name)
+          # The attribute isn't whitelisted.
+
+          if allow_data_attributes && attr_name.start_with?('data-')
+            # Arbitrary data attributes are allowed. If this is a data
+            # attribute, continue.
+            next if attr_name =~ REGEX_DATA_ATTR
+          end
+
+          # Either the attribute isn't a data attribute or arbitrary data
+          # attributes aren't allowed. Remove the attribute.
+          attr.unlink
+          next
+        end
+
+        # The attribute is whitelisted.
 
-          # Remove any attributes that use unacceptable protocols.
-          if @protocols.include?(name) && @protocols[name].include?(attr_name)
-            attr_protocols = @protocols[name][attr_name]
+        # Remove any attributes that use unacceptable protocols.
+        if @protocols.include?(name) && @protocols[name].include?(attr_name)
+          attr_protocols = @protocols[name][attr_name]
 
-            if attr.value =~ REGEX_PROTOCOL
-              attr.unlink unless attr_protocols.include?($1.downcase)
-            else
-              attr.unlink unless attr_protocols.include?(:relative)
+          if attr.value =~ REGEX_PROTOCOL
+            unless attr_protocols.include?($1.downcase)
+              attr.unlink
+              next
             end
-          end
-        else
-          # The attribute isn't whitelisted.
 
-          if allow_data_attributes && attr_name.start_with?('data-')
-            # Arbitrary data attributes are allowed. Verify that the attribute
-            # is a valid data attribute.
-            attr.unlink unless attr_name =~ REGEX_DATA_ATTR
           else
-            # Either the attribute isn't a data attribute, or arbitrary data
-            # attributes aren't allowed. Remove the attribute.
-            attr.unlink
+            unless attr_protocols.include?(:relative)
+              attr.unlink
+              next
+            end
           end
+
+          # Leading and trailing whitespace around URLs is ignored at parse
+          # time. Stripping it here prevents it from being escaped by the
+          # libxml2 workaround below.
+          attr.value = attr.value.strip
+        end
+
+        # libxml2 >= 2.9.2 doesn't escape comments within some attributes, in an
+        # attempt to preserve server-side includes. This can result in XSS since
+        # an unescaped double quote can allow an attacker to inject a
+        # non-whitelisted attribute.
+        #
+        # Sanitize works around this by implementing its own escaping for
+        # affected attributes, some of which can exist on any element and some
+        # of which can only exist on `<a>` elements.
+        #
+        # The relevant libxml2 code is here:
+        # <https://github.com/GNOME/libxml2/commit/960f0e275616cadc29671a218d7fb9b69eb35588>
+        if UNSAFE_LIBXML_ATTRS_GLOBAL.include?(attr_name) ||
+            (name == 'a' && UNSAFE_LIBXML_ATTRS_A.include?(attr_name))
+
+          attr.value = attr.value.gsub(UNSAFE_LIBXML_ESCAPE_REGEX, UNSAFE_LIBXML_ESCAPE_CHARS)
         end
       end
     end

programming_language: Ruby
filename: test_clean_element.rb
change_type: ModificationType.MODIFY
diff: @@ -234,7 +234,7 @@ describe 'Sanitize::Transformers::CleanElement' do
 
     it 'should not choke on valueless attributes' do
       @s.fragment('foo <a href>foo</a> bar')
-        .must_equal 'foo <a href="" rel="nofollow">foo</a> bar'
+        .must_equal 'foo <a href rel="nofollow">foo</a> bar'
     end
 
     it 'should downcase attribute names' do
@@ -300,6 +300,16 @@ describe 'Sanitize::Transformers::CleanElement' do
       }).must_equal input
     end
 
+    it "should not allow relative URLs when relative URLs aren't whitelisted" do
+      input = '<a href="/foo/bar">Link</a>'
+
+      Sanitize.fragment(input,
+        :elements   => ['a'],
+        :attributes => {'a' => ['href']},
+        :protocols  => {'a' => {'href' => ['http']}}
+      ).must_equal '<a>Link</a>'
+    end
+
     it 'should allow relative URLs containing colons when the colon is not in the first path segment' do
       input = '<a href="/wiki/Special:Random">Random Page</a>'
 

programming_language: Ruby
filename: test_malicious_html.rb
change_type: ModificationType.MODIFY
diff: @@ -125,4 +125,68 @@ describe 'Malicious HTML' do
         must_equal '&lt;alert("XSS");//&lt;'
     end
   end
+
+  # libxml2 >= 2.9.2 doesn't escape comments within some attributes, in an
+  # attempt to preserve server-side includes. This can result in XSS since an
+  # unescaped double quote can allow an attacker to inject a non-whitelisted
+  # attribute. Sanitize works around this by implementing its own escaping for
+  # affected attributes.
+  #
+  # The relevant libxml2 code is here:
+  # <https://github.com/GNOME/libxml2/commit/960f0e275616cadc29671a218d7fb9b69eb35588>
+  describe 'unsafe libxml2 server-side includes in attributes' do
+    tag_configs = [
+      {
+        tag_name: 'a',
+        escaped_attrs: %w[ action href src name ],
+        unescaped_attrs: []
+      },
+
+      {
+        tag_name: 'div',
+        escaped_attrs: %w[ action href src ],
+        unescaped_attrs: %w[ name ]
+      }
+    ]
+
+    before do
+      @s = Sanitize.new({
+        elements: %w[ a div ],
+
+        attributes: {
+          all: %w[ action href src name ]
+        }
+      })
+    end
+
+    tag_configs.each do |tag_config|
+      tag_name = tag_config[:tag_name]
+
+      tag_config[:escaped_attrs].each do |attr_name|
+        input = %[<#{tag_name} #{attr_name}='examp<!--" onmouseover=alert(1)>-->le.com'>foo</#{tag_name}>]
+
+        it 'should escape unsafe characters in attributes' do
+          @s.fragment(input).must_equal(%[<#{tag_name} #{attr_name}="examp<!--%22%20onmouseover=alert(1)>-->le.com">foo</#{tag_name}>])
+        end
+
+        it 'should round-trip to the same output' do
+          output = @s.fragment(input)
+          @s.fragment(output).must_equal(output)
+        end
+      end
+
+      tag_config[:unescaped_attrs].each do |attr_name|
+        input = %[<#{tag_name} #{attr_name}='examp<!--" onmouseover=alert(1)>-->le.com'>foo</#{tag_name}>]
+
+        it 'should not escape characters unnecessarily' do
+          @s.fragment(input).must_equal(input)
+        end
+
+        it 'should round-trip to the same output' do
+          output = @s.fragment(input)
+          @s.fragment(output).must_equal(output)
+        end
+      end
+    end
+  end
 end

programming_language: Ruby