Skip to content

Instantly share code, notes, and snippets.

@amitu
Last active September 6, 2018 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitu/5ee8aec5630c319e79a07d67ab52746a to your computer and use it in GitHub Desktop.
Save amitu/5ee8aec5630c319e79a07d67ab52746a to your computer and use it in GitHub Desktop.
SQL Injection Demonstration In Python
acko=# create table tmp_foo (id int);
CREATE TABLE
acko=# insert into tmp_foo values (1);
INSERT 0 1
acko=# insert into tmp_foo values (2);
INSERT 0 1
acko=# insert into tmp_foo values (3);
INSERT 0 1
acko=# select * from tmp_foo;
 id 
----
  1
  2
  3
(3 rows)
In [1]: from django.db import connection
In [2]: conn = connection.cursor()
In [5]: conn.execute("select count(*) from tmp_foo")
In [6]: conn.fetchone()
Out[6]: (3,)
In [7]: conn.execute("select count(*) from tmp_foo where id > 1")
In [8]: conn.fetchone()
Out[8]: (2,)
In [9]: id = "1"
In [10]: conn.execute("select count(*) from tmp_foo where id > %s" % id)
In [11]: conn.fetchone()
Out[11]: (2,)
In [9]: id = "1"
In [10]: conn.execute("select count(*) from tmp_foo where id > %s", (id, ))
In [11]: conn.fetchone()
Out[11]: (2,)
In [24]: id = "1; delete from tmp_foo"
In [25]: conn.execute("select count(*) from tmp_foo where id > %s" % id)
In [26]: conn.fetchall()
...
ProgrammingError: no results to fetch
acko=# select * from tmp_foo;
 id 
----
(0 rows)
acko=# insert into tmp_foo values (1);
INSERT 0 1
acko=# insert into tmp_foo values (2);
INSERT 0 1
acko=# insert into tmp_foo values (3);
INSERT 0 1
acko=# select * from tmp_foo;
 id 
----
  1
  2
  3
(3 rows)
In [27]: conn.execute("select count(*) from tmp_foo where id > %s", (id, ))
...
DataError: invalid input syntax for integer: "1; delete from tmp_foo"
LINE 1: select count(*) from tmp_foo where id > '1; delete from tmp_...
acko=# select * from tmp_foo;
 id 
----
  1
  2
  3
(3 rows)
@asitacko
Copy link

asitacko commented Sep 6, 2018

immaculate and accurate explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment