티스토리 수익 글 보기

티스토리 수익 글 보기

[1.5.x] Fixed queries that may return unexpected results on MySQL due… · django/django@985434f · GitHub
Skip to content

Commit 985434f

Browse files
mxsashatimgraham
authored andcommitted
[1.5.x] Fixed queries that may return unexpected results on MySQL due to typecasting.
This is a security fix. Disclosure will follow shortly. Backport of 75c0d4e from master
1 parent 6872f42 commit 985434f

File tree

6 files changed

+155
2
lines changed

6 files changed

+155
2
lines changed

django/db/models/fields/__init__.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,12 @@ def __init__(self, verbose_name=None, name=None, path='', match=None,
934934
kwargs['max_length'] = kwargs.get('max_length', 100)
935935
Field.__init__(self, verbose_name, name, **kwargs)
936936

937+
def get_prep_value(self, value):
938+
value = super(FilePathField, self).get_prep_value(value)
939+
if value is None:
940+
return None
941+
return six.text_type(value)
942+
937943
def formfield(self, **kwargs):
938944
defaults = {
939945
'path': self.path,
@@ -1035,6 +1041,12 @@ def __init__(self, *args, **kwargs):
10351041
kwargs['max_length'] = 15
10361042
Field.__init__(self, *args, **kwargs)
10371043

1044+
def get_prep_value(self, value):
1045+
value = super(IPAddressField, self).get_prep_value(value)
1046+
if value is None:
1047+
return None
1048+
return six.text_type(value)
1049+
10381050
def get_internal_type(self):
10391051
return "IPAddressField"
10401052

@@ -1072,12 +1084,14 @@ def get_db_prep_value(self, value, connection, prepared=False):
10721084
return value or None
10731085

10741086
def get_prep_value(self, value):
1087+
if value is None:
1088+
return value
10751089
if value and ':' in value:
10761090
try:
10771091
return clean_ipv6_address(value, self.unpack_ipv4)
10781092
except exceptions.ValidationError:
10791093
pass
1080-
return value
1094+
return six.text_type(value)
10811095

10821096
def formfield(self, **kwargs):
10831097
defaults = {'form_class': forms.GenericIPAddressField}

docs/howto/custom-model-fields.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,16 @@ For example::
501501
return ''.join([''.join(l) for l in (value.north,
502502
value.east, value.south, value.west)])
503503

504+
.. warning::
505+
506+
If your custom field uses the ``CHAR``, ``VARCHAR`` or ``TEXT``
507+
types for MySQL, you must make sure that :meth:`.get_prep_value`
508+
always returns a string type. MySQL performs flexible and unexpected
509+
matching when a query is performed on these types and the provided
510+
value is an integer, which can cause queries to include unexpected
511+
objects in their results. This problem cannot occur if you always
512+
return a string type from :meth:`.get_prep_value`.
513+
504514
Converting query values to database values
505515
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506516

docs/ref/databases.txt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,22 @@ MySQL does not support the ``NOWAIT`` option to the ``SELECT ... FOR UPDATE``
429429
statement. If ``select_for_update()`` is used with ``nowait=True`` then a
430430
``DatabaseError`` will be raised.
431431

432+
Automatic typecasting can cause unexpected results
433+
--------------------------------------------------
434+
435+
When performing a query on a string type, but with an integer value, MySQL will
436+
coerce the types of all values in the table to an integer before performing the
437+
comparison. If your table contains the values ``'abc'``, ``'def'`` and you
438+
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
439+
will match the value ``'abc1'``. Therefore, string type fields included in Django
440+
will always cast the value to a string before using it in a query.
441+
442+
If you implement custom model fields that inherit from :class:`~django.db.models.Field`
443+
directly, are overriding :meth:`~django.db.models.Field.get_prep_value`, or use
444+
:meth:`extra() <django.db.models.query.QuerySet.extra>` or
445+
:meth:`raw() <django.db.models.Manager.raw>`, you should ensure that you
446+
perform the appropriate typecasting.
447+
432448
.. _sqlite-notes:
433449

434450
SQLite notes

docs/ref/models/querysets.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,16 @@ of the arguments is required, but you should use at least one of them.
10681068

10691069
Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
10701070

1071+
.. warning::
1072+
1073+
If you are performing queries on MySQL, note that MySQL's silent type coercion
1074+
may cause unexpected results when mixing types. If you query on a string
1075+
type column, but with an integer value, MySQL will coerce the types of all values
1076+
in the table to an integer before performing the comparison. For example, if your
1077+
table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
1078+
both rows will match. To prevent this, perform the correct typecasting
1079+
before using the value in a query.
1080+
10711081
defer
10721082
~~~~~
10731083

docs/topics/db/sql.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ options that make it very powerful.
6666
database, but does nothing to enforce that. If the query does not
6767
return rows, a (possibly cryptic) error will result.
6868

69+
.. warning::
70+
71+
If you are performing queries on MySQL, note that MySQL's silent type coercion
72+
may cause unexpected results when mixing types. If you query on a string
73+
type column, but with an integer value, MySQL will coerce the types of all values
74+
in the table to an integer before performing the comparison. For example, if your
75+
table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
76+
both rows will match. To prevent this, perform the correct typecasting
77+
before using the value in a query.
78+
6979
Mapping query fields to model fields
7080
------------------------------------
7181

tests/regressiontests/model_fields/tests.py

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,15 @@
66
from django import test
77
from django import forms
88
from django.core.exceptions import ValidationError
9+
from django.db.models.fields import (
10+
AutoField, BigIntegerField, BooleanField, CharField,
11+
CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField,
12+
EmailField, FilePathField, FloatField, IntegerField, IPAddressField,
13+
GenericIPAddressField, NullBooleanField, PositiveIntegerField,
14+
PositiveSmallIntegerField, SlugField, SmallIntegerField, TextField,
15+
TimeField, URLField)
916
from django.db import models
10-
from django.db.models.fields.files import FieldFile
17+
from django.db.models.fields.files import FileField, ImageField, FieldFile
1118
from django.utils import six
1219
from django.utils import unittest
1320

@@ -414,3 +421,89 @@ def test_changed(self):
414421
field = d._meta.get_field('myfile')
415422
field.save_form_data(d, 'else.txt')
416423
self.assertEqual(d.myfile, 'else.txt')
424+
425+
426+
class PrepValueTest(test.TestCase):
427+
def test_AutoField(self):
428+
self.assertIsInstance(AutoField(primary_key=True).get_prep_value(1), int)
429+
430+
@unittest.skipIf(six.PY3, "Python 3 has no `long` type.")
431+
def test_BigIntegerField(self):
432+
self.assertIsInstance(BigIntegerField().get_prep_value(long(9999999999999999999)), long)
433+
434+
def test_BooleanField(self):
435+
self.assertIsInstance(BooleanField().get_prep_value(True), bool)
436+
437+
def test_CharField(self):
438+
self.assertIsInstance(CharField().get_prep_value(''), six.text_type)
439+
self.assertIsInstance(CharField().get_prep_value(0), six.text_type)
440+
441+
def test_CommaSeparatedIntegerField(self):
442+
self.assertIsInstance(CommaSeparatedIntegerField().get_prep_value('1,2'), six.text_type)
443+
self.assertIsInstance(CommaSeparatedIntegerField().get_prep_value(0), six.text_type)
444+
445+
def test_DateField(self):
446+
self.assertIsInstance(DateField().get_prep_value(datetime.date.today()), datetime.date)
447+
448+
def test_DateTimeField(self):
449+
self.assertIsInstance(DateTimeField().get_prep_value(datetime.datetime.now()), datetime.datetime)
450+
451+
def test_DecimalField(self):
452+
self.assertIsInstance(DecimalField().get_prep_value(Decimal('1.2')), Decimal)
453+
454+
def test_EmailField(self):
455+
self.assertIsInstance(EmailField().get_prep_value('mailbox@domain.com'), six.text_type)
456+
457+
def test_FileField(self):
458+
self.assertIsInstance(FileField().get_prep_value('filename.ext'), six.text_type)
459+
self.assertIsInstance(FileField().get_prep_value(0), six.text_type)
460+
461+
def test_FilePathField(self):
462+
self.assertIsInstance(FilePathField().get_prep_value('tests.py'), six.text_type)
463+
self.assertIsInstance(FilePathField().get_prep_value(0), six.text_type)
464+
465+
def test_FloatField(self):
466+
self.assertIsInstance(FloatField().get_prep_value(1.2), float)
467+
468+
def test_ImageField(self):
469+
self.assertIsInstance(ImageField().get_prep_value('filename.ext'), six.text_type)
470+
471+
def test_IntegerField(self):
472+
self.assertIsInstance(IntegerField().get_prep_value(1), int)
473+
474+
def test_IPAddressField(self):
475+
self.assertIsInstance(IPAddressField().get_prep_value('127.0.0.1'), six.text_type)
476+
self.assertIsInstance(IPAddressField().get_prep_value(0), six.text_type)
477+
478+
def test_GenericIPAddressField(self):
479+
self.assertIsInstance(GenericIPAddressField().get_prep_value('127.0.0.1'), six.text_type)
480+
self.assertIsInstance(GenericIPAddressField().get_prep_value(0), six.text_type)
481+
482+
def test_NullBooleanField(self):
483+
self.assertIsInstance(NullBooleanField().get_prep_value(True), bool)
484+
485+
def test_PositiveIntegerField(self):
486+
self.assertIsInstance(PositiveIntegerField().get_prep_value(1), int)
487+
488+
def test_PositiveSmallIntegerField(self):
489+
self.assertIsInstance(PositiveSmallIntegerField().get_prep_value(1), int)
490+
491+
def test_SlugField(self):
492+
self.assertIsInstance(SlugField().get_prep_value('slug'), six.text_type)
493+
self.assertIsInstance(SlugField().get_prep_value(0), six.text_type)
494+
495+
def test_SmallIntegerField(self):
496+
self.assertIsInstance(SmallIntegerField().get_prep_value(1), int)
497+
498+
def test_TextField(self):
499+
self.assertIsInstance(TextField().get_prep_value('Abc'), six.text_type)
500+
self.assertIsInstance(TextField().get_prep_value(0), six.text_type)
501+
502+
def test_TimeField(self):
503+
self.assertIsInstance(
504+
TimeField().get_prep_value(datetime.datetime.now().time()),
505+
datetime.time)
506+
507+
def test_URLField(self):
508+
self.assertIsInstance(URLField().get_prep_value('http://domain.com'), six.text_type)
509+

0 commit comments

Comments
 (0)