File: password-dos.diff

package info (click to toggle)
python-django 1.4.5-1%2Bdeb7u16
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 44,168 kB
  • sloc: python: 140,205; xml: 659; makefile: 160; sh: 145; sql: 7
file content (371 lines) | stat: -rw-r--r-- 13,504 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
Origin: https://github.com/django/django/commit/3f3d887a6844ec2db743fee64c9e53e04d39a368#L1L349
Date: 2013-09-15
Description: Ensure that passwords are never long enough for a DoS.
 * Limit the password length to 4096 bytes
 * Password hashers will raise a ValueError
 * django.contrib.auth forms will fail validation
 * Document in release notes that this is a backwards incompatible change

Thanks to Josh Wright for the report, and Donald Stufft for the patch.

Some changes were stripped from this patch since they also apply fixes to
UnsaltedSHA1PasswordHasher which is not shipped in the version of Django
in Debian.

--- a/django/contrib/auth/forms.py
+++ b/django/contrib/auth/forms.py
@@ -8,7 +8,10 @@
 
 from django.contrib.auth import authenticate
 from django.contrib.auth.models import User
-from django.contrib.auth.hashers import UNUSABLE_PASSWORD, is_password_usable, get_hasher
+from django.contrib.auth.hashers import (
+    MAXIMUM_PASSWORD_LENGTH, UNUSABLE_PASSWORD,
+    is_password_usable, get_hasher
+)
 from django.contrib.auth.tokens import default_token_generator
 from django.contrib.sites.models import get_current_site
 
@@ -70,10 +73,11 @@
             'invalid': _("This value may contain only letters, numbers and "
                          "@/./+/-/_ characters.")})
     password1 = forms.CharField(label=_("Password"),
-        widget=forms.PasswordInput)
+        widget=forms.PasswordInput, max_length=MAXIMUM_PASSWORD_LENGTH)
     password2 = forms.CharField(label=_("Password confirmation"),
         widget=forms.PasswordInput,
-        help_text = _("Enter the same password as above, for verification."))
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+        help_text=_("Enter the same password as above, for verification."))
 
     class Meta:
         model = User
@@ -137,7 +141,11 @@
     username/password logins.
     """
     username = forms.CharField(label=_("Username"), max_length=30)
-    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
+    password = forms.CharField(
+        label=_("Password"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
 
     error_messages = {
         'invalid_login': _("Please enter a correct username and password. "
@@ -250,10 +258,16 @@
     error_messages = {
         'password_mismatch': _("The two password fields didn't match."),
     }
-    new_password1 = forms.CharField(label=_("New password"),
-                                    widget=forms.PasswordInput)
-    new_password2 = forms.CharField(label=_("New password confirmation"),
-                                    widget=forms.PasswordInput)
+    new_password1 = forms.CharField(
+        label=_("New password"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
+    new_password2 = forms.CharField(
+        label=_("New password confirmation"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
 
     def __init__(self, user, *args, **kwargs):
         self.user = user
@@ -284,8 +298,11 @@
         'password_incorrect': _("Your old password was entered incorrectly. "
                                 "Please enter it again."),
     })
-    old_password = forms.CharField(label=_("Old password"),
-                                   widget=forms.PasswordInput)
+    old_password = forms.CharField(
+        label=_("Old password"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
 
     def clean_old_password(self):
         """
@@ -307,10 +324,16 @@
     error_messages = {
         'password_mismatch': _("The two password fields didn't match."),
     }
-    password1 = forms.CharField(label=_("Password"),
-                                widget=forms.PasswordInput)
-    password2 = forms.CharField(label=_("Password (again)"),
-                                widget=forms.PasswordInput)
+    password1 = forms.CharField(
+        label=_("Password"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
+    password2 = forms.CharField(
+        label=_("Password (again)"),
+        widget=forms.PasswordInput,
+        max_length=MAXIMUM_PASSWORD_LENGTH,
+    )
 
     def __init__(self, user, *args, **kwargs):
         self.user = user
--- a/django/contrib/auth/hashers.py
+++ b/django/contrib/auth/hashers.py
@@ -1,3 +1,4 @@
+import functools
 import hashlib
 
 from django.conf import settings
@@ -11,10 +12,23 @@
 
 
 UNUSABLE_PASSWORD = '!'  # This will never be a valid encoded hash
+MAXIMUM_PASSWORD_LENGTH = 4096  # The maximum length a password can be to prevent DoS
 HASHERS = None  # lazily loaded from PASSWORD_HASHERS
 PREFERRED_HASHER = None  # defaults to first item in PASSWORD_HASHERS
 
 
+def password_max_length(max_length):
+    def inner(fn):
+        @functools.wraps(fn)
+        def wrapper(self, password, *args, **kwargs):
+            if len(password) > max_length:
+                raise ValueError("Invalid password; Must be less than or equal"
+                                 " to %d bytes" % max_length)
+            return fn(self, password, *args, **kwargs)
+        return wrapper
+    return inner
+
+
 def is_password_usable(encoded):
     return (encoded is not None and encoded != UNUSABLE_PASSWORD)
 
@@ -197,6 +211,7 @@
     iterations = 10000
     digest = hashlib.sha256
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt, iterations=None):
         assert password
         assert salt and '$' not in salt
@@ -206,6 +221,7 @@
         hash = hash.encode('base64').strip()
         return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         algorithm, iterations, salt, hash = encoded.split('$', 3)
         assert algorithm == self.algorithm
@@ -251,11 +267,13 @@
         bcrypt = self._load_library()
         return bcrypt.gensalt(self.rounds)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt):
         bcrypt = self._load_library()
         data = bcrypt.hashpw(password, salt)
         return "%s$%s" % (self.algorithm, data)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         algorithm, data = encoded.split('$', 1)
         assert algorithm == self.algorithm
@@ -280,12 +298,14 @@
     """
     algorithm = "sha1"
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt):
         assert password
         assert salt and '$' not in salt
         hash = hashlib.sha1(salt + password).hexdigest()
         return "%s$%s$%s" % (self.algorithm, salt, hash)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         algorithm, salt, hash = encoded.split('$', 2)
         assert algorithm == self.algorithm
@@ -308,12 +328,14 @@
     """
     algorithm = "md5"
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt):
         assert password
         assert salt and '$' not in salt
         hash = hashlib.md5(salt + password).hexdigest()
         return "%s$%s$%s" % (self.algorithm, salt, hash)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         algorithm, salt, hash = encoded.split('$', 2)
         assert algorithm == self.algorithm
@@ -344,15 +366,18 @@
     def salt(self):
         return ''
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt):
         return hashlib.md5(password).hexdigest()
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         if len(encoded) == 37 and encoded.startswith('md5$$'):
             encoded = encoded[5:]
         encoded_2 = self.encode(password, '')
         return constant_time_compare(encoded, encoded_2)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def safe_summary(self, encoded):
         return SortedDict([
             (_('algorithm'), self.algorithm),
@@ -372,6 +397,7 @@
     def salt(self):
         return get_random_string(2)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def encode(self, password, salt):
         crypt = self._load_library()
         assert len(salt) == 2
@@ -379,6 +405,7 @@
         # we don't need to store the salt, but Django used to do this
         return "%s$%s$%s" % (self.algorithm, '', data)
 
+    @password_max_length(MAXIMUM_PASSWORD_LENGTH)
     def verify(self, password, encoded):
         crypt = self._load_library()
         algorithm, salt, data = encoded.split('$', 2)
@@ -393,4 +420,3 @@
             (_('salt'), salt),
             (_('hash'), mask_hash(data, show=3)),
         ])
-
--- a/django/contrib/auth/tests/hashers.py
+++ b/django/contrib/auth/tests/hashers.py
@@ -1,7 +1,8 @@
 from django.conf.global_settings import PASSWORD_HASHERS as default_hashers
 from django.contrib.auth.hashers import (is_password_usable, 
     check_password, make_password, PBKDF2PasswordHasher, load_hashers,
-    PBKDF2SHA1PasswordHasher, get_hasher, UNUSABLE_PASSWORD)
+    PBKDF2SHA1PasswordHasher, get_hasher, UNUSABLE_PASSWORD,
+    MAXIMUM_PASSWORD_LENGTH, password_max_length)
 from django.utils import unittest
 from django.utils.unittest import skipUnless
 from django.test.utils import override_settings
@@ -28,6 +29,12 @@
         self.assertTrue(is_password_usable(encoded))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+        )
 
     def test_pkbdf2(self):
         encoded = make_password('letmein', 'seasalt', 'pbkdf2_sha256')
@@ -36,6 +43,14 @@
         self.assertTrue(is_password_usable(encoded))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            "seasalt",
+            "pbkdf2_sha256",
+        )
 
     def test_sha1(self):
         encoded = make_password('letmein', 'seasalt', 'sha1')
@@ -44,6 +59,14 @@
         self.assertTrue(is_password_usable(encoded))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            "seasalt",
+            "sha1",
+        )
 
     def test_md5(self):
         encoded = make_password('letmein', 'seasalt', 'md5')
@@ -52,6 +75,14 @@
         self.assertTrue(is_password_usable(encoded))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            "seasalt",
+            "md5",
+        )
 
     def test_unsalted_md5(self):
         encoded = make_password('letmein', 'seasalt', 'unsalted_md5')
@@ -64,6 +95,14 @@
         self.assertTrue(is_password_usable(alt_encoded))
         self.assertTrue(check_password(u'letmein', alt_encoded))
         self.assertFalse(check_password('letmeinz', alt_encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            "",
+            "unsalted_md5",
+        )
 
     @skipUnless(crypt, "no crypt module to generate password.")
     def test_crypt(self):
@@ -72,6 +111,14 @@
         self.assertTrue(is_password_usable(encoded))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            "seasalt",
+            "crypt",
+        )
 
     @skipUnless(bcrypt, "py-bcrypt not installed")
     def test_bcrypt(self):
@@ -80,6 +127,13 @@
         self.assertTrue(encoded.startswith('bcrypt$'))
         self.assertTrue(check_password(u'letmein', encoded))
         self.assertFalse(check_password('letmeinz', encoded))
+        # Long password
+        self.assertRaises(
+            ValueError,
+            make_password,
+            b"1" * (MAXIMUM_PASSWORD_LENGTH + 1),
+            hasher="bcrypt",
+        )
 
     def test_unusable(self):
         encoded = make_password(None)
@@ -95,6 +149,14 @@
             make_password('letmein', hasher='lolcat')
         self.assertRaises(ValueError, doit)
 
+    def test_max_password_length_decorator(self):
+        @password_max_length(10)
+        def encode(s, password, salt):
+            return True
+
+        self.assertTrue(encode(None, b"1234", b"1234"))
+        self.assertRaises(ValueError, encode, None, b"1234567890A", b"1234")
+
     def test_low_level_pkbdf2(self):
         hasher = PBKDF2PasswordHasher()
         encoded = hasher.encode('letmein', 'seasalt')