plain 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plain/README.md +33 -0
- plain/__main__.py +5 -0
- plain/assets/README.md +56 -0
- plain/assets/__init__.py +6 -0
- plain/assets/finders.py +233 -0
- plain/assets/preflight.py +14 -0
- plain/assets/storage.py +916 -0
- plain/assets/utils.py +52 -0
- plain/assets/whitenoise/__init__.py +5 -0
- plain/assets/whitenoise/base.py +259 -0
- plain/assets/whitenoise/compress.py +189 -0
- plain/assets/whitenoise/media_types.py +137 -0
- plain/assets/whitenoise/middleware.py +197 -0
- plain/assets/whitenoise/responders.py +286 -0
- plain/assets/whitenoise/storage.py +178 -0
- plain/assets/whitenoise/string_utils.py +13 -0
- plain/cli/README.md +123 -0
- plain/cli/__init__.py +3 -0
- plain/cli/cli.py +439 -0
- plain/cli/formatting.py +61 -0
- plain/cli/packages.py +73 -0
- plain/cli/print.py +9 -0
- plain/cli/startup.py +33 -0
- plain/csrf/README.md +3 -0
- plain/csrf/middleware.py +466 -0
- plain/csrf/views.py +10 -0
- plain/debug.py +23 -0
- plain/exceptions.py +242 -0
- plain/forms/README.md +14 -0
- plain/forms/__init__.py +8 -0
- plain/forms/boundfield.py +58 -0
- plain/forms/exceptions.py +11 -0
- plain/forms/fields.py +1030 -0
- plain/forms/forms.py +297 -0
- plain/http/README.md +1 -0
- plain/http/__init__.py +51 -0
- plain/http/cookie.py +20 -0
- plain/http/multipartparser.py +743 -0
- plain/http/request.py +754 -0
- plain/http/response.py +719 -0
- plain/internal/__init__.py +0 -0
- plain/internal/files/README.md +3 -0
- plain/internal/files/__init__.py +3 -0
- plain/internal/files/base.py +161 -0
- plain/internal/files/locks.py +127 -0
- plain/internal/files/move.py +102 -0
- plain/internal/files/temp.py +79 -0
- plain/internal/files/uploadedfile.py +150 -0
- plain/internal/files/uploadhandler.py +254 -0
- plain/internal/files/utils.py +78 -0
- plain/internal/handlers/__init__.py +0 -0
- plain/internal/handlers/base.py +133 -0
- plain/internal/handlers/exception.py +145 -0
- plain/internal/handlers/wsgi.py +216 -0
- plain/internal/legacy/__init__.py +0 -0
- plain/internal/legacy/__main__.py +12 -0
- plain/internal/legacy/management/__init__.py +414 -0
- plain/internal/legacy/management/base.py +692 -0
- plain/internal/legacy/management/color.py +113 -0
- plain/internal/legacy/management/commands/__init__.py +0 -0
- plain/internal/legacy/management/commands/collectstatic.py +297 -0
- plain/internal/legacy/management/sql.py +67 -0
- plain/internal/legacy/management/utils.py +175 -0
- plain/json.py +40 -0
- plain/logs/README.md +24 -0
- plain/logs/__init__.py +5 -0
- plain/logs/configure.py +39 -0
- plain/logs/loggers.py +74 -0
- plain/logs/utils.py +46 -0
- plain/middleware/README.md +3 -0
- plain/middleware/__init__.py +0 -0
- plain/middleware/clickjacking.py +52 -0
- plain/middleware/common.py +87 -0
- plain/middleware/gzip.py +64 -0
- plain/middleware/security.py +64 -0
- plain/packages/README.md +41 -0
- plain/packages/__init__.py +4 -0
- plain/packages/config.py +259 -0
- plain/packages/registry.py +438 -0
- plain/paginator.py +187 -0
- plain/preflight/README.md +3 -0
- plain/preflight/__init__.py +38 -0
- plain/preflight/compatibility/__init__.py +0 -0
- plain/preflight/compatibility/django_4_0.py +20 -0
- plain/preflight/files.py +19 -0
- plain/preflight/messages.py +88 -0
- plain/preflight/registry.py +72 -0
- plain/preflight/security/__init__.py +0 -0
- plain/preflight/security/base.py +268 -0
- plain/preflight/security/csrf.py +40 -0
- plain/preflight/urls.py +117 -0
- plain/runtime/README.md +75 -0
- plain/runtime/__init__.py +61 -0
- plain/runtime/global_settings.py +199 -0
- plain/runtime/user_settings.py +353 -0
- plain/signals/README.md +14 -0
- plain/signals/__init__.py +5 -0
- plain/signals/dispatch/__init__.py +9 -0
- plain/signals/dispatch/dispatcher.py +320 -0
- plain/signals/dispatch/license.txt +35 -0
- plain/signing.py +299 -0
- plain/templates/README.md +20 -0
- plain/templates/__init__.py +6 -0
- plain/templates/core.py +24 -0
- plain/templates/jinja/README.md +227 -0
- plain/templates/jinja/__init__.py +22 -0
- plain/templates/jinja/defaults.py +119 -0
- plain/templates/jinja/extensions.py +39 -0
- plain/templates/jinja/filters.py +28 -0
- plain/templates/jinja/globals.py +19 -0
- plain/test/README.md +3 -0
- plain/test/__init__.py +16 -0
- plain/test/client.py +985 -0
- plain/test/utils.py +255 -0
- plain/urls/README.md +3 -0
- plain/urls/__init__.py +40 -0
- plain/urls/base.py +118 -0
- plain/urls/conf.py +94 -0
- plain/urls/converters.py +66 -0
- plain/urls/exceptions.py +9 -0
- plain/urls/resolvers.py +731 -0
- plain/utils/README.md +3 -0
- plain/utils/__init__.py +0 -0
- plain/utils/_os.py +52 -0
- plain/utils/cache.py +327 -0
- plain/utils/connection.py +84 -0
- plain/utils/crypto.py +76 -0
- plain/utils/datastructures.py +345 -0
- plain/utils/dateformat.py +329 -0
- plain/utils/dateparse.py +154 -0
- plain/utils/dates.py +76 -0
- plain/utils/deconstruct.py +54 -0
- plain/utils/decorators.py +90 -0
- plain/utils/deprecation.py +6 -0
- plain/utils/duration.py +44 -0
- plain/utils/email.py +12 -0
- plain/utils/encoding.py +235 -0
- plain/utils/functional.py +456 -0
- plain/utils/hashable.py +26 -0
- plain/utils/html.py +401 -0
- plain/utils/http.py +374 -0
- plain/utils/inspect.py +73 -0
- plain/utils/ipv6.py +46 -0
- plain/utils/itercompat.py +8 -0
- plain/utils/module_loading.py +69 -0
- plain/utils/regex_helper.py +353 -0
- plain/utils/safestring.py +72 -0
- plain/utils/termcolors.py +221 -0
- plain/utils/text.py +518 -0
- plain/utils/timesince.py +138 -0
- plain/utils/timezone.py +244 -0
- plain/utils/tree.py +126 -0
- plain/validators.py +603 -0
- plain/views/README.md +268 -0
- plain/views/__init__.py +18 -0
- plain/views/base.py +107 -0
- plain/views/csrf.py +24 -0
- plain/views/errors.py +25 -0
- plain/views/exceptions.py +4 -0
- plain/views/forms.py +76 -0
- plain/views/objects.py +229 -0
- plain/views/redirect.py +72 -0
- plain/views/templates.py +66 -0
- plain/wsgi.py +11 -0
- plain-0.1.0.dist-info/LICENSE +85 -0
- plain-0.1.0.dist-info/METADATA +51 -0
- plain-0.1.0.dist-info/RECORD +169 -0
- plain-0.1.0.dist-info/WHEEL +4 -0
- plain-0.1.0.dist-info/entry_points.txt +3 -0
plain/cli/startup.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import plain.runtime
|
|
2
|
+
|
|
3
|
+
plain.runtime.setup()
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _print_bold(s):
|
|
7
|
+
print("\033[1m", end="")
|
|
8
|
+
print(s)
|
|
9
|
+
print("\033[0m", end="")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _print_italic(s):
|
|
13
|
+
print("\x1B[3m", end="")
|
|
14
|
+
print(s)
|
|
15
|
+
print("\x1B[0m", end="")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_print_bold("\n⬣ Welcome to the Plain shell! ⬣")
|
|
19
|
+
|
|
20
|
+
_app_shell = plain.runtime.APP_PATH / "shell.py"
|
|
21
|
+
|
|
22
|
+
if _app_shell.exists():
|
|
23
|
+
_print_bold("\nImporting custom app/shell.py")
|
|
24
|
+
contents = _app_shell.read_text()
|
|
25
|
+
|
|
26
|
+
for line in contents.splitlines():
|
|
27
|
+
_print_italic(f">>> {line}")
|
|
28
|
+
|
|
29
|
+
print()
|
|
30
|
+
|
|
31
|
+
# Import * so we get everything that file imported
|
|
32
|
+
# (which is mostly the point of having it)
|
|
33
|
+
from app.shell import * # noqa
|
plain/csrf/README.md
ADDED
plain/csrf/middleware.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cross Site Request Forgery Middleware.
|
|
3
|
+
|
|
4
|
+
This module provides a middleware that implements protection
|
|
5
|
+
against request forgeries from other sites.
|
|
6
|
+
"""
|
|
7
|
+
import logging
|
|
8
|
+
import string
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from urllib.parse import urlparse
|
|
11
|
+
|
|
12
|
+
from plain.exceptions import DisallowedHost, ImproperlyConfigured
|
|
13
|
+
from plain.http import HttpHeaders, UnreadablePostError
|
|
14
|
+
from plain.logs import log_response
|
|
15
|
+
from plain.runtime import settings
|
|
16
|
+
from plain.utils.cache import patch_vary_headers
|
|
17
|
+
from plain.utils.crypto import constant_time_compare, get_random_string
|
|
18
|
+
from plain.utils.functional import cached_property
|
|
19
|
+
from plain.utils.http import is_same_domain
|
|
20
|
+
from plain.utils.regex_helper import _lazy_re_compile
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("plain.security.csrf")
|
|
23
|
+
# This matches if any character is not in CSRF_ALLOWED_CHARS.
|
|
24
|
+
invalid_token_chars_re = _lazy_re_compile("[^a-zA-Z0-9]")
|
|
25
|
+
|
|
26
|
+
REASON_BAD_ORIGIN = "Origin checking failed - %s does not match any trusted origins."
|
|
27
|
+
REASON_NO_REFERER = "Referer checking failed - no Referer."
|
|
28
|
+
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
|
|
29
|
+
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
|
|
30
|
+
REASON_CSRF_TOKEN_MISSING = "CSRF token missing."
|
|
31
|
+
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
|
|
32
|
+
REASON_INSECURE_REFERER = (
|
|
33
|
+
"Referer checking failed - Referer is insecure while host is secure."
|
|
34
|
+
)
|
|
35
|
+
# The reason strings below are for passing to InvalidTokenFormat. They are
|
|
36
|
+
# phrases without a subject because they can be in reference to either the CSRF
|
|
37
|
+
# cookie or non-cookie token.
|
|
38
|
+
REASON_INCORRECT_LENGTH = "has incorrect length"
|
|
39
|
+
REASON_INVALID_CHARACTERS = "has invalid characters"
|
|
40
|
+
|
|
41
|
+
CSRF_SECRET_LENGTH = 32
|
|
42
|
+
CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
|
|
43
|
+
CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
|
|
44
|
+
CSRF_SESSION_KEY = "_csrftoken"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _get_new_csrf_string():
|
|
48
|
+
return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _mask_cipher_secret(secret):
|
|
52
|
+
"""
|
|
53
|
+
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
|
|
54
|
+
token by adding a mask and applying it to the secret.
|
|
55
|
+
"""
|
|
56
|
+
mask = _get_new_csrf_string()
|
|
57
|
+
chars = CSRF_ALLOWED_CHARS
|
|
58
|
+
pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
|
|
59
|
+
cipher = "".join(chars[(x + y) % len(chars)] for x, y in pairs)
|
|
60
|
+
return mask + cipher
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _unmask_cipher_token(token):
|
|
64
|
+
"""
|
|
65
|
+
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
|
|
66
|
+
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
|
|
67
|
+
the second half to produce the original secret.
|
|
68
|
+
"""
|
|
69
|
+
mask = token[:CSRF_SECRET_LENGTH]
|
|
70
|
+
token = token[CSRF_SECRET_LENGTH:]
|
|
71
|
+
chars = CSRF_ALLOWED_CHARS
|
|
72
|
+
pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in mask))
|
|
73
|
+
return "".join(chars[x - y] for x, y in pairs) # Note negative values are ok
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _add_new_csrf_cookie(request):
|
|
77
|
+
"""Generate a new random CSRF_COOKIE value, and add it to request.META."""
|
|
78
|
+
csrf_secret = _get_new_csrf_string()
|
|
79
|
+
request.META.update(
|
|
80
|
+
{
|
|
81
|
+
"CSRF_COOKIE": csrf_secret,
|
|
82
|
+
"CSRF_COOKIE_NEEDS_UPDATE": True,
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
return csrf_secret
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get_token(request):
|
|
89
|
+
"""
|
|
90
|
+
Return the CSRF token required for a POST form. The token is an
|
|
91
|
+
alphanumeric value. A new token is created if one is not already set.
|
|
92
|
+
|
|
93
|
+
A side effect of calling this function is to make the csrf_protect
|
|
94
|
+
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
|
|
95
|
+
header to the outgoing response. For this reason, you may need to use this
|
|
96
|
+
function lazily, as is done by the csrf context processor.
|
|
97
|
+
"""
|
|
98
|
+
if "CSRF_COOKIE" in request.META:
|
|
99
|
+
csrf_secret = request.META["CSRF_COOKIE"]
|
|
100
|
+
# Since the cookie is being used, flag to send the cookie in
|
|
101
|
+
# process_response() (even if the client already has it) in order to
|
|
102
|
+
# renew the expiry timer.
|
|
103
|
+
request.META["CSRF_COOKIE_NEEDS_UPDATE"] = True
|
|
104
|
+
else:
|
|
105
|
+
csrf_secret = _add_new_csrf_cookie(request)
|
|
106
|
+
return _mask_cipher_secret(csrf_secret)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def rotate_token(request):
|
|
110
|
+
"""
|
|
111
|
+
Change the CSRF token in use for a request - should be done on login
|
|
112
|
+
for security purposes.
|
|
113
|
+
"""
|
|
114
|
+
_add_new_csrf_cookie(request)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class InvalidTokenFormat(Exception):
|
|
118
|
+
def __init__(self, reason):
|
|
119
|
+
self.reason = reason
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _check_token_format(token):
|
|
123
|
+
"""
|
|
124
|
+
Raise an InvalidTokenFormat error if the token has an invalid length or
|
|
125
|
+
characters that aren't allowed. The token argument can be a CSRF cookie
|
|
126
|
+
secret or non-cookie CSRF token, and either masked or unmasked.
|
|
127
|
+
"""
|
|
128
|
+
if len(token) not in (CSRF_TOKEN_LENGTH, CSRF_SECRET_LENGTH):
|
|
129
|
+
raise InvalidTokenFormat(REASON_INCORRECT_LENGTH)
|
|
130
|
+
# Make sure all characters are in CSRF_ALLOWED_CHARS.
|
|
131
|
+
if invalid_token_chars_re.search(token):
|
|
132
|
+
raise InvalidTokenFormat(REASON_INVALID_CHARACTERS)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _does_token_match(request_csrf_token, csrf_secret):
|
|
136
|
+
"""
|
|
137
|
+
Return whether the given CSRF token matches the given CSRF secret, after
|
|
138
|
+
unmasking the token if necessary.
|
|
139
|
+
|
|
140
|
+
This function assumes that the request_csrf_token argument has been
|
|
141
|
+
validated to have the correct length (CSRF_SECRET_LENGTH or
|
|
142
|
+
CSRF_TOKEN_LENGTH characters) and allowed characters, and that if it has
|
|
143
|
+
length CSRF_TOKEN_LENGTH, it is a masked secret.
|
|
144
|
+
"""
|
|
145
|
+
# Only unmask tokens that are exactly CSRF_TOKEN_LENGTH characters long.
|
|
146
|
+
if len(request_csrf_token) == CSRF_TOKEN_LENGTH:
|
|
147
|
+
request_csrf_token = _unmask_cipher_token(request_csrf_token)
|
|
148
|
+
assert len(request_csrf_token) == CSRF_SECRET_LENGTH
|
|
149
|
+
return constant_time_compare(request_csrf_token, csrf_secret)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class RejectRequest(Exception):
|
|
153
|
+
def __init__(self, reason):
|
|
154
|
+
self.reason = reason
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class CsrfViewMiddleware:
|
|
158
|
+
"""
|
|
159
|
+
Require a present and correct csrfmiddlewaretoken for POST requests that
|
|
160
|
+
have a CSRF cookie, and set an outgoing CSRF cookie.
|
|
161
|
+
|
|
162
|
+
This middleware should be used in conjunction with the {% csrf_token %}
|
|
163
|
+
template tag.
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
def __init__(self, get_response):
|
|
167
|
+
self.get_response = get_response
|
|
168
|
+
|
|
169
|
+
def __call__(self, request):
|
|
170
|
+
try:
|
|
171
|
+
csrf_secret = self._get_secret(request)
|
|
172
|
+
except InvalidTokenFormat:
|
|
173
|
+
_add_new_csrf_cookie(request)
|
|
174
|
+
else:
|
|
175
|
+
if csrf_secret is not None:
|
|
176
|
+
# Use the same secret next time. If the secret was originally
|
|
177
|
+
# masked, this also causes it to be replaced with the unmasked
|
|
178
|
+
# form, but only in cases where the secret is already getting
|
|
179
|
+
# saved anyways.
|
|
180
|
+
request.META["CSRF_COOKIE"] = csrf_secret
|
|
181
|
+
|
|
182
|
+
response = self.get_response(request)
|
|
183
|
+
|
|
184
|
+
if request.META.get("CSRF_COOKIE_NEEDS_UPDATE"):
|
|
185
|
+
self._set_csrf_cookie(request, response)
|
|
186
|
+
# Unset the flag to prevent _set_csrf_cookie() from being
|
|
187
|
+
# unnecessarily called again in process_response() by other
|
|
188
|
+
# instances of CsrfViewMiddleware. This can happen e.g. when both a
|
|
189
|
+
# decorator and middleware are used. However,
|
|
190
|
+
# CSRF_COOKIE_NEEDS_UPDATE is still respected in subsequent calls
|
|
191
|
+
# e.g. in case rotate_token() is called in process_response() later
|
|
192
|
+
# by custom middleware but before those subsequent calls.
|
|
193
|
+
request.META["CSRF_COOKIE_NEEDS_UPDATE"] = False
|
|
194
|
+
|
|
195
|
+
return response
|
|
196
|
+
|
|
197
|
+
@cached_property
|
|
198
|
+
def csrf_trusted_origins_hosts(self):
|
|
199
|
+
return [
|
|
200
|
+
urlparse(origin).netloc.lstrip("*")
|
|
201
|
+
for origin in settings.CSRF_TRUSTED_ORIGINS
|
|
202
|
+
]
|
|
203
|
+
|
|
204
|
+
@cached_property
|
|
205
|
+
def allowed_origins_exact(self):
|
|
206
|
+
return {origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin}
|
|
207
|
+
|
|
208
|
+
@cached_property
|
|
209
|
+
def allowed_origin_subdomains(self):
|
|
210
|
+
"""
|
|
211
|
+
A mapping of allowed schemes to list of allowed netlocs, where all
|
|
212
|
+
subdomains of the netloc are allowed.
|
|
213
|
+
"""
|
|
214
|
+
allowed_origin_subdomains = defaultdict(list)
|
|
215
|
+
for parsed in (
|
|
216
|
+
urlparse(origin)
|
|
217
|
+
for origin in settings.CSRF_TRUSTED_ORIGINS
|
|
218
|
+
if "*" in origin
|
|
219
|
+
):
|
|
220
|
+
allowed_origin_subdomains[parsed.scheme].append(parsed.netloc.lstrip("*"))
|
|
221
|
+
return allowed_origin_subdomains
|
|
222
|
+
|
|
223
|
+
def _reject(self, request, reason):
|
|
224
|
+
from .views import CsrfFailureView
|
|
225
|
+
|
|
226
|
+
response = CsrfFailureView.as_view()(request, reason=reason)
|
|
227
|
+
log_response(
|
|
228
|
+
"Forbidden (%s): %s",
|
|
229
|
+
reason,
|
|
230
|
+
request.path,
|
|
231
|
+
response=response,
|
|
232
|
+
request=request,
|
|
233
|
+
logger=logger,
|
|
234
|
+
)
|
|
235
|
+
return response
|
|
236
|
+
|
|
237
|
+
def _get_secret(self, request):
|
|
238
|
+
"""
|
|
239
|
+
Return the CSRF secret originally associated with the request, or None
|
|
240
|
+
if it didn't have one.
|
|
241
|
+
|
|
242
|
+
If the CSRF_USE_SESSIONS setting is false, raises InvalidTokenFormat if
|
|
243
|
+
the request's secret has invalid characters or an invalid length.
|
|
244
|
+
"""
|
|
245
|
+
if settings.CSRF_USE_SESSIONS:
|
|
246
|
+
try:
|
|
247
|
+
csrf_secret = request.session.get(CSRF_SESSION_KEY)
|
|
248
|
+
except AttributeError:
|
|
249
|
+
raise ImproperlyConfigured(
|
|
250
|
+
"CSRF_USE_SESSIONS is enabled, but request.session is not "
|
|
251
|
+
"set. SessionMiddleware must appear before CsrfViewMiddleware "
|
|
252
|
+
"in MIDDLEWARE."
|
|
253
|
+
)
|
|
254
|
+
else:
|
|
255
|
+
try:
|
|
256
|
+
csrf_secret = request.COOKIES[settings.CSRF_COOKIE_NAME]
|
|
257
|
+
except KeyError:
|
|
258
|
+
csrf_secret = None
|
|
259
|
+
else:
|
|
260
|
+
# This can raise InvalidTokenFormat.
|
|
261
|
+
_check_token_format(csrf_secret)
|
|
262
|
+
if csrf_secret is None:
|
|
263
|
+
return None
|
|
264
|
+
return csrf_secret
|
|
265
|
+
|
|
266
|
+
def _set_csrf_cookie(self, request, response):
|
|
267
|
+
if settings.CSRF_USE_SESSIONS:
|
|
268
|
+
if request.session.get(CSRF_SESSION_KEY) != request.META["CSRF_COOKIE"]:
|
|
269
|
+
request.session[CSRF_SESSION_KEY] = request.META["CSRF_COOKIE"]
|
|
270
|
+
else:
|
|
271
|
+
response.set_cookie(
|
|
272
|
+
settings.CSRF_COOKIE_NAME,
|
|
273
|
+
request.META["CSRF_COOKIE"],
|
|
274
|
+
max_age=settings.CSRF_COOKIE_AGE,
|
|
275
|
+
domain=settings.CSRF_COOKIE_DOMAIN,
|
|
276
|
+
path=settings.CSRF_COOKIE_PATH,
|
|
277
|
+
secure=settings.CSRF_COOKIE_SECURE,
|
|
278
|
+
httponly=settings.CSRF_COOKIE_HTTPONLY,
|
|
279
|
+
samesite=settings.CSRF_COOKIE_SAMESITE,
|
|
280
|
+
)
|
|
281
|
+
# Set the Vary header since content varies with the CSRF cookie.
|
|
282
|
+
patch_vary_headers(response, ("Cookie",))
|
|
283
|
+
|
|
284
|
+
def _origin_verified(self, request):
|
|
285
|
+
request_origin = request.META["HTTP_ORIGIN"]
|
|
286
|
+
try:
|
|
287
|
+
good_host = request.get_host()
|
|
288
|
+
except DisallowedHost:
|
|
289
|
+
pass
|
|
290
|
+
else:
|
|
291
|
+
good_origin = "{}://{}".format(
|
|
292
|
+
"https" if request.is_secure() else "http",
|
|
293
|
+
good_host,
|
|
294
|
+
)
|
|
295
|
+
if request_origin == good_origin:
|
|
296
|
+
return True
|
|
297
|
+
if request_origin in self.allowed_origins_exact:
|
|
298
|
+
return True
|
|
299
|
+
try:
|
|
300
|
+
parsed_origin = urlparse(request_origin)
|
|
301
|
+
except ValueError:
|
|
302
|
+
return False
|
|
303
|
+
request_scheme = parsed_origin.scheme
|
|
304
|
+
request_netloc = parsed_origin.netloc
|
|
305
|
+
return any(
|
|
306
|
+
is_same_domain(request_netloc, host)
|
|
307
|
+
for host in self.allowed_origin_subdomains.get(request_scheme, ())
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
def _check_referer(self, request):
|
|
311
|
+
referer = request.META.get("HTTP_REFERER")
|
|
312
|
+
if referer is None:
|
|
313
|
+
raise RejectRequest(REASON_NO_REFERER)
|
|
314
|
+
|
|
315
|
+
try:
|
|
316
|
+
referer = urlparse(referer)
|
|
317
|
+
except ValueError:
|
|
318
|
+
raise RejectRequest(REASON_MALFORMED_REFERER)
|
|
319
|
+
|
|
320
|
+
# Make sure we have a valid URL for Referer.
|
|
321
|
+
if "" in (referer.scheme, referer.netloc):
|
|
322
|
+
raise RejectRequest(REASON_MALFORMED_REFERER)
|
|
323
|
+
|
|
324
|
+
# Ensure that our Referer is also secure.
|
|
325
|
+
if referer.scheme != "https":
|
|
326
|
+
raise RejectRequest(REASON_INSECURE_REFERER)
|
|
327
|
+
|
|
328
|
+
if any(
|
|
329
|
+
is_same_domain(referer.netloc, host)
|
|
330
|
+
for host in self.csrf_trusted_origins_hosts
|
|
331
|
+
):
|
|
332
|
+
return
|
|
333
|
+
# Allow matching the configured cookie domain.
|
|
334
|
+
good_referer = (
|
|
335
|
+
settings.SESSION_COOKIE_DOMAIN
|
|
336
|
+
if settings.CSRF_USE_SESSIONS
|
|
337
|
+
else settings.CSRF_COOKIE_DOMAIN
|
|
338
|
+
)
|
|
339
|
+
if good_referer is None:
|
|
340
|
+
# If no cookie domain is configured, allow matching the current
|
|
341
|
+
# host:port exactly if it's permitted by ALLOWED_HOSTS.
|
|
342
|
+
try:
|
|
343
|
+
# request.get_host() includes the port.
|
|
344
|
+
good_referer = request.get_host()
|
|
345
|
+
except DisallowedHost:
|
|
346
|
+
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
|
347
|
+
else:
|
|
348
|
+
server_port = request.get_port()
|
|
349
|
+
if server_port not in ("443", "80"):
|
|
350
|
+
good_referer = f"{good_referer}:{server_port}"
|
|
351
|
+
|
|
352
|
+
if not is_same_domain(referer.netloc, good_referer):
|
|
353
|
+
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
|
354
|
+
|
|
355
|
+
def _bad_token_message(self, reason, token_source):
|
|
356
|
+
if token_source != "POST":
|
|
357
|
+
# Assume it is a settings.CSRF_HEADER_NAME value.
|
|
358
|
+
header_name = HttpHeaders.parse_header_name(token_source)
|
|
359
|
+
token_source = f"the {header_name!r} HTTP header"
|
|
360
|
+
return f"CSRF token from {token_source} {reason}."
|
|
361
|
+
|
|
362
|
+
def _check_token(self, request):
|
|
363
|
+
# Access csrf_secret via self._get_secret() as rotate_token() may have
|
|
364
|
+
# been called by an authentication middleware during the
|
|
365
|
+
# process_request() phase.
|
|
366
|
+
try:
|
|
367
|
+
csrf_secret = self._get_secret(request)
|
|
368
|
+
except InvalidTokenFormat as exc:
|
|
369
|
+
raise RejectRequest(f"CSRF cookie {exc.reason}.")
|
|
370
|
+
|
|
371
|
+
if csrf_secret is None:
|
|
372
|
+
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
|
|
373
|
+
# and in this way we can avoid all CSRF attacks, including login
|
|
374
|
+
# CSRF.
|
|
375
|
+
raise RejectRequest(REASON_NO_CSRF_COOKIE)
|
|
376
|
+
|
|
377
|
+
# Check non-cookie token for match.
|
|
378
|
+
request_csrf_token = ""
|
|
379
|
+
if request.method == "POST":
|
|
380
|
+
try:
|
|
381
|
+
request_csrf_token = request.POST.get("csrfmiddlewaretoken", "")
|
|
382
|
+
except UnreadablePostError:
|
|
383
|
+
# Handle a broken connection before we've completed reading the
|
|
384
|
+
# POST data. process_view shouldn't raise any exceptions, so
|
|
385
|
+
# we'll ignore and serve the user a 403 (assuming they're still
|
|
386
|
+
# listening, which they probably aren't because of the error).
|
|
387
|
+
pass
|
|
388
|
+
|
|
389
|
+
if request_csrf_token == "":
|
|
390
|
+
# Fall back to X-CSRFToken, to make things easier for AJAX, and
|
|
391
|
+
# possible for PUT/DELETE.
|
|
392
|
+
try:
|
|
393
|
+
# This can have length CSRF_SECRET_LENGTH or CSRF_TOKEN_LENGTH,
|
|
394
|
+
# depending on whether the client obtained the token from
|
|
395
|
+
# the DOM or the cookie (and if the cookie, whether the cookie
|
|
396
|
+
# was masked or unmasked).
|
|
397
|
+
request_csrf_token = request.META[settings.CSRF_HEADER_NAME]
|
|
398
|
+
except KeyError:
|
|
399
|
+
raise RejectRequest(REASON_CSRF_TOKEN_MISSING)
|
|
400
|
+
token_source = settings.CSRF_HEADER_NAME
|
|
401
|
+
else:
|
|
402
|
+
token_source = "POST"
|
|
403
|
+
|
|
404
|
+
try:
|
|
405
|
+
_check_token_format(request_csrf_token)
|
|
406
|
+
except InvalidTokenFormat as exc:
|
|
407
|
+
reason = self._bad_token_message(exc.reason, token_source)
|
|
408
|
+
raise RejectRequest(reason)
|
|
409
|
+
|
|
410
|
+
if not _does_token_match(request_csrf_token, csrf_secret):
|
|
411
|
+
reason = self._bad_token_message("incorrect", token_source)
|
|
412
|
+
raise RejectRequest(reason)
|
|
413
|
+
|
|
414
|
+
def process_view(self, request, callback, callback_args, callback_kwargs):
|
|
415
|
+
# Wait until request.META["CSRF_COOKIE"] has been manipulated before
|
|
416
|
+
# bailing out, so that get_token still works
|
|
417
|
+
if getattr(callback, "csrf_exempt", False):
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
# Assume that anything not defined as 'safe' by RFC 9110 needs protection
|
|
421
|
+
if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"):
|
|
422
|
+
return None
|
|
423
|
+
|
|
424
|
+
if getattr(request, "_dont_enforce_csrf_checks", False):
|
|
425
|
+
# Mechanism to turn off CSRF checks for test suite. It comes after
|
|
426
|
+
# the creation of CSRF cookies, so that everything else continues
|
|
427
|
+
# to work exactly the same (e.g. cookies are sent, etc.), but
|
|
428
|
+
# before any branches that call the _reject method.
|
|
429
|
+
return None
|
|
430
|
+
|
|
431
|
+
# Reject the request if the Origin header doesn't match an allowed
|
|
432
|
+
# value.
|
|
433
|
+
if "HTTP_ORIGIN" in request.META:
|
|
434
|
+
if not self._origin_verified(request):
|
|
435
|
+
return self._reject(
|
|
436
|
+
request, REASON_BAD_ORIGIN % request.META["HTTP_ORIGIN"]
|
|
437
|
+
)
|
|
438
|
+
elif request.is_secure():
|
|
439
|
+
# If the Origin header wasn't provided, reject HTTPS requests if
|
|
440
|
+
# the Referer header doesn't match an allowed value.
|
|
441
|
+
#
|
|
442
|
+
# Suppose user visits http://example.com/
|
|
443
|
+
# An active network attacker (man-in-the-middle, MITM) sends a
|
|
444
|
+
# POST form that targets https://example.com/detonate-bomb/ and
|
|
445
|
+
# submits it via JavaScript.
|
|
446
|
+
#
|
|
447
|
+
# The attacker will need to provide a CSRF cookie and token, but
|
|
448
|
+
# that's no problem for a MITM and the session-independent secret
|
|
449
|
+
# we're using. So the MITM can circumvent the CSRF protection. This
|
|
450
|
+
# is true for any HTTP connection, but anyone using HTTPS expects
|
|
451
|
+
# better! For this reason, for https://example.com/ we need
|
|
452
|
+
# additional protection that treats http://example.com/ as
|
|
453
|
+
# completely untrusted. Under HTTPS, Barth et al. found that the
|
|
454
|
+
# Referer header is missing for same-domain requests in only about
|
|
455
|
+
# 0.2% of cases or less, so we can use strict Referer checking.
|
|
456
|
+
try:
|
|
457
|
+
self._check_referer(request)
|
|
458
|
+
except RejectRequest as exc:
|
|
459
|
+
return self._reject(request, exc.reason)
|
|
460
|
+
|
|
461
|
+
try:
|
|
462
|
+
self._check_token(request)
|
|
463
|
+
except RejectRequest as exc:
|
|
464
|
+
return self._reject(request, exc.reason)
|
|
465
|
+
|
|
466
|
+
return None
|
plain/csrf/views.py
ADDED
plain/debug.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from pprint import pformat
|
|
2
|
+
|
|
3
|
+
from markupsafe import escape
|
|
4
|
+
|
|
5
|
+
from plain.http import Response
|
|
6
|
+
from plain.views.exceptions import ResponseException
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def dd(obj):
|
|
10
|
+
"""
|
|
11
|
+
Dump and die.
|
|
12
|
+
|
|
13
|
+
Dump the object and raise a ResponseException with the dump as the response content.
|
|
14
|
+
"""
|
|
15
|
+
dump_str = pformat(obj)
|
|
16
|
+
|
|
17
|
+
print(f"Dumping object:\n{dump_str}")
|
|
18
|
+
|
|
19
|
+
response = Response()
|
|
20
|
+
response.status_code = 500
|
|
21
|
+
response.content = escape(dump_str)
|
|
22
|
+
response.content_type = "text/html"
|
|
23
|
+
raise ResponseException(response)
|