Negating an AND expression.

The basic database QUERY expression for a simple login is:
[sql]
SELECT * FROM users WHERE username = 'phillip' AND password = 'taco'
[/sql]
Which boils down to: "Login if T ∧ T" where in this case the first T is the result the database returns when username is in the database and the second is the result T is where password is in the database.

Note that, because of precedence rules for logical operators:

T ∧ F = F

but

T ∨ T ∧ F = T ∨ (T ∧ F) = T

and more importantly

F ∨ T ∨ T ∧ F = F ∨ T ∨ (T ∧ F) = T

Assume that "Phillip Cramer" is a username in the database.
Now, if we are able to inject the ' character into the query string, we can inject
{% highlight ruby %}
name = "Philip Cramer' or '1'='1"
{% endhighlight %}
and we change the query into:
{% highlight sql %}
SELECT * FROM users WHERE username = 'Philip Cramer' or '1'='1' AND password = 'taco'
{% endhighlight %}
Which will yield a success because we have changed the boolean part of query to be T ∨ T ∧ F. However, this approach isn't as useful, because we had to know that Philip Cramer was in the database.

If we modify the name to be:
{% highlight ruby %}
name = "waffle' or 1=1 or '1'='1"
{% endhighlight %}
then this makes the query:
{% highlight sql %}
SELECT * FROM users WHERE username = 'wrongname' or 1=1 or '1'='1' AND City = 'wrongpassword'
{% endhighlight %}
Which will yield a success because we have changed the boolean part of query to be F ∨ T ∨ T ∧ F. The first F is generated because 'wrongname' isn't in the database and the second F is generated because 'wrongpassword' isn't in the database either; but this doesn't matter because the whole statement is true.

  • Note there is no reason that this has to be SQL. Any database that takes creates queries from unchecked user input can have users create tautologies.

  • Modification: if the SQL string is unescaped such as:
    {% highlight sql %}
    SELECT * FROM users WHERE username = phillip AND password = taco
    {% endhighlight %}
    Then you can leave out the ' injections.