1

I'm getting the error in the title when trying to select a cookie value from a table in a postgresql database, and I've no idea why. Selecting other fields in this table work fine.

Here's the line where it is breaking:

user=UniqueUser.find(:all, :select => 'DISTINCT visitor_id', :conditions=> "visitor_id=#{visitorid}")

The column is defined as character varying(255)

Here's the error:

187/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapt
ers/abstract_adapter.rb:219:in `log': PGError: ERROR:  syntax error at or near "
c5a" (ActiveRecord::StatementInvalid)
LINE 1: ...M "unique_users" WHERE (visitor_id=d5fb0ff2-319e-4c5a-b07c-a...

It seems like Rails should put quotes around the data field in the where clause.

I'm certainly not a Rails expert, so it could be something really simple that I am doing wrong, and appreciate any help.

2
  • what is you SQL output ? Commented Oct 28, 2010 at 13:07
  • Hi shingara, the only output that I see is what I pasted above. ...M "unique_users" WHERE (visitor_id=d5fb0ff2-319e-4c5a-b07c-a... There is probably a way to get the exact statement, but I don't know it, and Swanand solved my problem, so I guess I won't worry about it now. Thanks for your help. Commented Oct 28, 2010 at 15:36

1 Answer 1

2

You aren't escaping your input properly. Try this:

user = UniqueUser.find(:all, :select => 'DISTINCT visitor_id', :conditions=> ['visitor_id = ?', visitorid])
Sign up to request clarification or add additional context in comments.

4 Comments

Congratulations, you have just exposed your app to SQL injection :)
Ariejan- If you have time to elaborate a bit, I'd appreciate it. I understand SQL injection, but not how it relates to this Rails example. Thanks!
The OP code has an injection vulnerability because the visitorid is injected directly into the SQL statement using #{ }. If some user somehow got the value 0 OR 1=1 into visitorid, your SQL statement would end up looking like this: SELECT visitor_id FROM visitors WHERE visitor_id = 1 OR 1=1, and the query would return a list of all user IDs in your system. Or worse, a more complex string could allow someone to execute a second query after the first, and get back any information they want. Prevent this by passing all variables to the SQL the Rails way, using question marks as shown above.
@Ariejan : Can you explain how SQL injection is possible in this case? :conditions => escapes user input, hence the ?, think of it as prepared query. In fact, the conditions array is used to avoid SQL injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.