A_Elric
A_Elric

Reputation: 3568

Is this Ruby PSQL safe from injection?

If I have the following PSQL statement via ruby:

user = User.find_by_email(params[:email])
sql2 = "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"email\" = \'#{params[:email]}\' LIMIT 1"
@result3 = Otherdb.connection.execute(sql2);

Fed by the following form:

<form action="/sessions" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="tj5rfiJG+yip8gXhMSq/RR/Znu+L/nhkGnqqK78wggRjI85zl4T/wBEkouY8XWlh2aylfKH0lZWjH282fc6Qdg==" />
    <div class="login">
      <h1>Login to Web App</h1>
      <p id="alert">User not present in db</p>
      <form method="post" action="">
        <p><label for="email">Email</label>
        <input type="text" name="email" id="email" /></p>
        <p><label for="password">Password</label>
        <input type="password" name="password" id="password" /></p>
        <p class="remember_me">
    <label for="remember_me">
     <input type="checkbox" name="remember_me" id="remember_me" value="1" />
     Remember me on this computer
    </label>
        </p>
        <p class="submit"><input type="submit" name="commit" value="Login" data-disable-with="Login" /></p>
      </form>
    </div>
    </form>

I have been able to generally escape the form by using ' followed by characters, but I can't seem to get any payloads to execute.

Is this secure, or is there a more complicated escape sequence for breaking out of the statement

Upvotes: 0

Views: 66

Answers (1)

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

Yes, it is definitely SQL injection. To test it you can pass SQL like '; select count(*) from users; in params[:email].

To avoid SQL injection you could rewrite your code like:

sql2 = User.where(email: params[:email]).limit(1).to_sql
@result3 = Otherdb.connection.execute(sql2)

Just let ActiveRecord escape and sanitize the query and the params for you.

Upvotes: 2

Related Questions