From 3eaea655a506ed035fab3d143aa918958cf52405 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Feb 2014 16:22:40 -0800 Subject: [PATCH] Correctly escape PostgreSQL arrays. Thanks Godfrey Chan for reporting this! Fixes: CVE-2014-0080 --- .../lib/active_record/connection_adapters/postgresql/cast.rb | 6 +++++- activerecord/test/cases/adapters/postgresql/datatype_test.rb | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb index a73f0ac..eac828b 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb @@ -138,12 +138,16 @@ module ActiveRecord end end + ARRAY_ESCAPE = "\\" * 2 * 2 # escape the backslash twice for PG arrays + def quote_and_escape(value) case value when "NULL" value else - "\"#{value.gsub(/"/,"\\\"")}\"" + value = value.gsub(/\\/, ARRAY_ESCAPE) + value.gsub!(/"/,"\\\"") + "\"#{value}\"" end end end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index 1b2f5f0..6c78a51 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -184,6 +184,14 @@ _SQL assert_equal :text, @first_array.column_for_attribute(:nicknames).type end + def test_array_escaping + unknown = %(foo\\",bar,baz,\\) + nicknames = ["hello_#{unknown}"] + ar = PostgresqlArray.create!(nicknames: nicknames, id: 100) + ar.reload + assert_equal nicknames, ar.nicknames + end + def test_data_type_of_range_types skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? assert_equal :daterange, @first_range.column_for_attribute(:date_range).type -- 1.8.4.3