|
| 1 | +"""This is copied from ql/python/ql/test/library-tests/web/django/test.py |
| 2 | +and a only a slight extension of ql/python/ql/src/Security/CWE-089/examples/sql_injection.py |
| 3 | +""" |
| 4 | + |
| 5 | +from django.conf.urls import url |
| 6 | +from django.db import connection, models |
| 7 | +from django.db.models.expressions import RawSQL |
| 8 | + |
| 9 | +class User(models.Model): |
| 10 | + pass |
| 11 | + |
| 12 | +def show_user(request, username): |
| 13 | + with connection.cursor() as cursor: |
| 14 | + # GOOD -- Using parameters |
| 15 | + cursor.execute("SELECT * FROM users WHERE username = %s", username) |
| 16 | + User.objects.raw("SELECT * FROM users WHERE username = %s", (username,)) |
| 17 | + |
| 18 | + # BAD -- Using string formatting |
| 19 | + cursor.execute("SELECT * FROM users WHERE username = '%s'" % username) |
| 20 | + |
| 21 | + # BAD -- other ways of executing raw SQL code with string interpolation |
| 22 | + User.objects.annotate(RawSQL("insert into names_file ('name') values ('%s')" % username)) |
| 23 | + User.objects.raw("insert into names_file ('name') values ('%s')" % username) |
| 24 | + User.objects.extra("insert into names_file ('name') values ('%s')" % username) |
| 25 | + |
| 26 | + # BAD (but currently no custom query to find this) |
| 27 | + # |
| 28 | + # It is exposed to SQL injection (https://docs.djangoproject.com/en/2.2/ref/models/querysets/#extra) |
| 29 | + # For example, using name = "; DROP ALL TABLES -- " |
| 30 | + # will result in SQL: SELECT * FROM name WHERE name = ''; DROP ALL TABLES -- '' |
| 31 | + # |
| 32 | + # This shouldn't be very widespread, since using a normal string will result in invalid SQL |
| 33 | + # Using name = "example", will result in SQL: SELECT * FROM name WHERE name = ''example'' |
| 34 | + # which in MySQL will give a syntax error |
| 35 | + # |
| 36 | + # When testing this out locally, none of the queries worked against SQLite3, but I could use |
| 37 | + # the SQL injection against MySQL. |
| 38 | + User.objects.raw("SELECT * FROM users WHERE username = '%s'", (username,)) |
| 39 | + |
| 40 | +urlpatterns = [url(r'^users/(?P<username>[^/]+)$', show_user)] |
0 commit comments