CVE-2012-2140 (published 2012-07-18T18:55Z)

The Mail gem before 2.4.3 for Ruby allows remote attackers to execute arbitrary commands via shell metacharacters in a (1) sendmail or (2) exim delivery.

Severity: HIGH
CVSS v2 base score: 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P)

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/mikel/mail
commit_details: repo_url: https://github.com/mikel/mail
author: Mikel Lindsaar
author_date: 2012-03-06 18:59:38+11:00
msg: Fix security vulnerability allowing command line exploit when using exim or sendmail from the command line
repository: repo_url: https://github.com/mikel/mail
repo_name: mikel/mail
description: A Really Ruby Mail Library
repo_language: Ruby
owner: mikel
file_changes: filename: mail.rb
change_type: ModificationType.MODIFY
diff: @@ -29,7 +29,7 @@ module Mail # :doc:
   require 'mail/core_extensions/nil'
   require 'mail/core_extensions/object'
   require 'mail/core_extensions/string'
-  require 'mail/core_extensions/shellwords' unless String.new.respond_to?(:shellescape)
+  require 'mail/core_extensions/shell_escape'
   require 'mail/core_extensions/smtp' if RUBY_VERSION < '1.9.3'
   require 'mail/indifferent_hash'
 

programming_language: Ruby
filename: shell_escape.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,56 @@
+# encoding: utf-8
+
+# The following is an adaptation of ruby 1.9.2's shellwords.rb file,
+# it is modified to include '+' in the allowed list to allow for
+# sendmail to accept email addresses as the sender with a + in them
+#
+module Mail
+  module ShellEscape
+    # Escapes a string so that it can be safely used in a Bourne shell
+    # command line.
+    #
+    # Note that a resulted string should be used unquoted and is not
+    # intended for use in double quotes nor in single quotes.
+    #
+    #   open("| grep #{Shellwords.escape(pattern)} file") { |pipe|
+    #     # ...
+    #   }
+    #
+    # +String#shellescape+ is a shorthand for this function.
+    #
+    #   open("| grep #{pattern.shellescape} file") { |pipe|
+    #     # ...
+    #   }
+    #
+    def escape_for_shell(str)
+      # An empty argument will be skipped, so return empty quotes.
+      return "''" if str.empty?
+
+      str = str.dup
+
+      # Process as a single byte sequence because not all shell
+      # implementations are multibyte aware.
+      str.gsub!(/([^A-Za-z0-9_\s\+\-.,:\/@\n])/n, "\\\\\\1")
+
+      # A LF cannot be escaped with a backslash because a backslash + LF
+      # combo is regarded as line continuation and simply ignored.
+      str.gsub!(/\n/, "'\n'")
+
+      return str
+    end
+
+    module_function :escape_for_shell
+  end
+end
+
+class String
+  # call-seq:
+  #   str.shellescape => string
+  #
+  # Escapes +str+ so that it can be safely used in a Bourne shell
+  # command line.  See +Shellwords::shellescape+ for details.
+  #
+  def escape_for_shell
+    Mail::ShellEscape.escape_for_shell(self)
+  end
+end
\ No newline at end of file

programming_language: Ruby
filename: shellwords.rb
change_type: ModificationType.DELETE
diff: @@ -1,57 +0,0 @@
-# encoding: utf-8
-
-# The following is imported from ruby 1.9.2 shellwords.rb
-#
-module Shellwords
-  # Escapes a string so that it can be safely used in a Bourne shell
-  # command line.
-  #
-  # Note that a resulted string should be used unquoted and is not
-  # intended for use in double quotes nor in single quotes.
-  #
-  #   open("| grep #{Shellwords.escape(pattern)} file") { |pipe|
-  #     # ...
-  #   }
-  #
-  # +String#shellescape+ is a shorthand for this function.
-  #
-  #   open("| grep #{pattern.shellescape} file") { |pipe|
-  #     # ...
-  #   }
-  #
-  def shellescape(str)
-    # An empty argument will be skipped, so return empty quotes.
-    return "''" if str.empty?
-
-    str = str.dup
-
-    # Process as a single byte sequence because not all shell
-    # implementations are multibyte aware.
-    str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
-
-    # A LF cannot be escaped with a backslash because a backslash + LF
-    # combo is regarded as line continuation and simply ignored.
-    str.gsub!(/\n/, "'\n'")
-
-    return str
-  end
-
-  module_function :shellescape
-
-  class << self
-    alias escape shellescape
-  end
-
-end
-
-class String
-  # call-seq:
-  #   str.shellescape => string
-  #
-  # Escapes +str+ so that it can be safely used in a Bourne shell
-  # command line.  See +Shellwords::shellescape+ for details.
-  #
-  def shellescape
-    Shellwords.escape(self)
-  end
-end
\ No newline at end of file

programming_language: unknown
filename: exim.rb
change_type: ModificationType.MODIFY
diff: @@ -1,12 +1,45 @@
 module Mail
 
+  # A delivery method implementation which sends via exim.
+  #
+  # To use this, first find out where the exim binary is on your computer,
+  # if you are on a mac or unix box, it is usually in /usr/sbin/exim, this will
+  # be your exim location.
+  #
+  #   Mail.defaults do
+  #     delivery_method :exim
+  #   end
+  #
+  # Or if your exim binary is not at '/usr/sbin/exim'
+  #
+  #   Mail.defaults do
+  #     delivery_method :exim, :location => '/absolute/path/to/your/exim'
+  #   end
+  #
+  # Then just deliver the email as normal:
+  #
+  #   Mail.deliver do
+  #     to 'mikel@test.lindsaar.net'
+  #     from 'ada@test.lindsaar.net'
+  #     subject 'testing exim'
+  #     body 'testing exim'
+  #   end
+  #
+  # Or by calling deliver on a Mail message
+  #
+  #   mail = Mail.new do
+  #     to 'mikel@test.lindsaar.net'
+  #     from 'ada@test.lindsaar.net'
+  #     subject 'testing exim'
+  #     body 'testing exim'
+  #   end
+  #
+  #   mail.deliver!
   class Exim < Sendmail
 
-    def deliver!(mail)
-      envelope_from = mail.return_path || mail.sender || mail.from_addrs.first
-      return_path = "-f \"#{envelope_from.to_s.shellescape}\"" if envelope_from
-      arguments = [settings[:arguments], return_path].compact.join(" ")
-      self.class.call(settings[:location], arguments, mail)
+    def initialize(values)
+      self.settings = { :location       => '/usr/sbin/exim',
+                        :arguments      => '-i -t' }.merge(values)
     end
 
     def self.call(path, arguments, mail)

programming_language: Ruby
filename: sendmail.rb
change_type: ModificationType.MODIFY
diff: @@ -45,14 +45,14 @@ module Mail
 
     def deliver!(mail)
       envelope_from = mail.return_path || mail.sender || mail.from_addrs.first
-      return_path = "-f \"#{envelope_from.to_s.gsub('"', '\"')}\"" if envelope_from
+      return_path = "-f " + '"' + envelope_from.escape_for_shell + '"' if envelope_from
 
       arguments = [settings[:arguments], return_path].compact.join(" ")
 
-      Sendmail.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(" "), mail)
+      self.class.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(" "), mail)
     end
 
-    def Sendmail.call(path, arguments, destinations, mail)
+    def self.call(path, arguments, destinations, mail)
       IO.popen("#{path} #{arguments} #{destinations}", "w+") do |io|
         io.puts mail.encoded.to_lf
         io.flush

programming_language: Ruby
filename: exim_spec.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,161 @@
+# encoding: utf-8
+require 'spec_helper'
+
+describe "exim delivery agent" do
+  
+  before(:each) do
+    # Reset all defaults back to original state
+    Mail.defaults do
+      delivery_method :smtp, { :address              => "localhost",
+                               :port                 => 25,
+                               :domain               => 'localhost.localdomain',
+                               :user_name            => nil,
+                               :password             => nil,
+                               :authentication       => nil,
+                               :enable_starttls_auto => true  }
+    end
+  end
+
+  it "should send an email using exim" do
+    Mail.defaults do
+      delivery_method :exim
+    end
+    
+    mail = Mail.new do
+      from    'roger@test.lindsaar.net'
+      to      'marcel@test.lindsaar.net, bob@test.lindsaar.net'
+      subject 'invalid RFC2822'
+    end
+    
+    Mail::Exim.should_receive(:call).with('/usr/sbin/exim', 
+                                          '-i -t -f "roger@test.lindsaar.net"', 
+                                          'marcel@test.lindsaar.net bob@test.lindsaar.net', 
+                                          mail)
+    mail.deliver!
+  end
+
+  describe "return path" do
+
+    it "should send an email with a return-path using exim" do
+      Mail.defaults do
+        delivery_method :exim
+      end
+
+      mail = Mail.new do
+        to "to@test.lindsaar.net"
+        from "from@test.lindsaar.net"
+        sender "sender@test.lindsaar.net"
+        subject "Can't set the return-path"
+        return_path "return@test.lindsaar.net"
+        message_id "<1234@test.lindsaar.net>"
+        body "body"
+      end
+      
+      Mail::Exim.should_receive(:call).with('/usr/sbin/exim',
+                                                '-i -t -f "return@test.lindsaar.net"', 
+                                                'to@test.lindsaar.net', 
+                                                mail)
+                                                
+      mail.deliver
+
+    end
+
+    it "should use the sender address is no return path is specified" do
+      Mail.defaults do
+        delivery_method :exim
+      end
+
+      mail = Mail.new do
+        to "to@test.lindsaar.net"
+        from "from@test.lindsaar.net"
+        sender "sender@test.lindsaar.net"
+        subject "Can't set the return-path"
+        message_id "<1234@test.lindsaar.net>"
+        body "body"
+      end
+
+      Mail::Exim.should_receive(:call).with('/usr/sbin/exim',
+                                                '-i -t -f "sender@test.lindsaar.net"', 
+                                                'to@test.lindsaar.net', 
+                                                mail)
+
+      mail.deliver
+    end
+    
+    it "should use the from address is no return path or sender are specified" do
+      Mail.defaults do
+        delivery_method :exim
+      end
+
+      mail = Mail.new do
+        to "to@test.lindsaar.net"
+        from "from@test.lindsaar.net"
+        subject "Can't set the return-path"
+        message_id "<1234@test.lindsaar.net>"
+        body "body"
+      end
+
+      Mail::Exim.should_receive(:call).with('/usr/sbin/exim',
+                                                '-i -t -f "from@test.lindsaar.net"', 
+                                                'to@test.lindsaar.net', 
+                                                mail)
+      mail.deliver
+    end
+
+    it "should escape the return path address" do
+      Mail.defaults do
+        delivery_method :exim
+      end
+
+      mail = Mail.new do
+        to 'to@test.lindsaar.net'
+        from '"from+suffix test"@test.lindsaar.net'
+        subject 'Can\'t set the return-path'
+        message_id '<1234@test.lindsaar.net>'
+        body 'body'
+      end
+
+      Mail::Exim.should_receive(:call).with('/usr/sbin/exim',
+                                                '-i -t -f "\"from+suffix test\"@test.lindsaar.net"',
+                                                'to@test.lindsaar.net',
+                                                mail)
+      mail.deliver
+    end
+  end
+
+  it "should still send an email if the settings have been set to nil" do
+    Mail.defaults do
+      delivery_method :exim, :arguments => nil
+    end
+    
+    mail = Mail.new do
+      from    'from@test.lindsaar.net'
+      to      'marcel@test.lindsaar.net, bob@test.lindsaar.net'
+      subject 'invalid RFC2822'
+    end
+    
+    Mail::Exim.should_receive(:call).with('/usr/sbin/exim', 
+                                              '-f "from@test.lindsaar.net"', 
+                                              'marcel@test.lindsaar.net bob@test.lindsaar.net', 
+                                              mail)
+    mail.deliver!
+  end
+
+  it "should escape evil haxxor attemptes" do
+    Mail.defaults do
+      delivery_method :exim, :arguments => nil
+    end
+    
+    mail = Mail.new do
+      from    '"foo\";touch /tmp/PWNED;\""@blah.com'
+      to      'marcel@test.lindsaar.net'
+      subject 'invalid RFC2822'
+    end
+    
+    Mail::Exim.should_receive(:call).with('/usr/sbin/exim', 
+                                              "-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"", 
+                                              'marcel@test.lindsaar.net', 
+                                              mail)
+    mail.deliver!
+  end
+end

programming_language: Ruby
filename: sendmail_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -123,7 +123,6 @@ describe "sendmail delivery agent" do
     end
   end
 
-
   it "should still send an email if the settings have been set to nil" do
     Mail.defaults do
       delivery_method :sendmail, :arguments => nil
@@ -141,4 +140,22 @@ describe "sendmail delivery agent" do
                                               mail)
     mail.deliver!
   end
+
+  it "should escape evil haxxor attemptes" do
+    Mail.defaults do
+      delivery_method :sendmail, :arguments => nil
+    end
+    
+    mail = Mail.new do
+      from    '"foo\";touch /tmp/PWNED;\""@blah.com'
+      to      'marcel@test.lindsaar.net'
+      subject 'invalid RFC2822'
+    end
+    
+    Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', 
+                                              "-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"", 
+                                              'marcel@test.lindsaar.net', 
+                                              mail)
+    mail.deliver!
+  end
 end

programming_language: Ruby
repo_url: https://github.com/mikel/mail
commit_details: repo_url: https://github.com/mikel/mail
author: Mikel Lindsaar
author_date: 2012-03-06 19:45:23+11:00
msg: Making sure that destinations are also properly escaped in all version of ruby
repository: repo_url: https://github.com/mikel/mail
repo_name: mikel/mail
description: A Really Ruby Mail Library
repo_language: Ruby
owner: mikel
file_changes: filename: sendmail.rb
change_type: ModificationType.MODIFY
diff: @@ -49,7 +49,7 @@ module Mail
 
       arguments = [settings[:arguments], return_path].compact.join(" ")
 
-      self.class.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(" "), mail)
+      self.class.call(settings[:location], arguments, mail.destinations.collect(&:escape_for_shell).join(" "), mail)
     end
 
     def self.call(path, arguments, destinations, mail)

programming_language: Ruby
filename: sendmail_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -148,13 +148,13 @@ describe "sendmail delivery agent" do
     
     mail = Mail.new do
       from    '"foo\";touch /tmp/PWNED;\""@blah.com'
-      to      'marcel@test.lindsaar.net'
+      to      '"foo\";touch /tmp/PWNED;\""@blah.com'
       subject 'invalid RFC2822'
     end
     
     Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', 
                                               "-f \"\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com\"", 
-                                              'marcel@test.lindsaar.net', 
+                                              "\\\"foo\\\\\\\"\\;touch /tmp/PWNED\\;\\\\\\\"\\\"@blah.com", 
                                               mail)
     mail.deliver!
   end

programming_language: Ruby