1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from webob
.exc
import HTTPForbidden
21 from wtforms
import Form
, HiddenField
, validators
23 from mediagoblin
import mg_globals
24 from mediagoblin
.meddleware
import BaseMeddleware
26 # Use the system (hardware-based) random number generator if it exists.
27 # -- this optimization is lifted from Django
28 if hasattr(random
, 'SystemRandom'):
29 getrandbits
= random
.SystemRandom().getrandbits
31 getrandbits
= random
.getrandbits
34 def csrf_exempt(func
):
35 """Decorate a Controller to exempt it from CSRF protection."""
37 func
.csrf_enabled
= False
42 """Simple form to handle rendering a CSRF token and confirming it
43 is included in the POST."""
45 csrf_token
= HiddenField("",
46 [validators
.Required()])
49 def render_csrf_form_token(request
):
50 """Render the CSRF token in a format suitable for inclusion in a
53 if 'CSRF_TOKEN' not in request
.environ
:
56 form
= CsrfForm(csrf_token
=request
.environ
['CSRF_TOKEN'])
58 return form
.csrf_token
61 class CsrfMeddleware(BaseMeddleware
):
62 """CSRF Protection Meddleware
64 Adds a CSRF Cookie to responses and verifies that it is present
65 and matches the form token for non-safe requests.
69 SAFE_HTTP_METHODS
= ("GET", "HEAD", "OPTIONS", "TRACE")
71 def process_request(self
, request
, controller
):
72 """For non-safe requests, confirm that the tokens are present
76 # get the token from the cookie
78 request
.environ
['CSRF_TOKEN'] = \
79 request
.cookies
[mg_globals
.app_config
['csrf_cookie_name']]
82 # if it doesn't exist, make a new one
83 request
.environ
['CSRF_TOKEN'] = self
._make
_token
(request
)
85 # if this is a non-"safe" request (ie, one that could have
86 # side effects), confirm that the CSRF tokens are present and
88 if (getattr(controller
, 'csrf_enabled', True) and
89 request
.method
not in self
.SAFE_HTTP_METHODS
and
90 ('gmg.verify_csrf' in request
.environ
or
91 'paste.testing' not in request
.environ
)
94 return self
.verify_tokens(request
)
96 def process_response(self
, request
, response
):
97 """Add the CSRF cookie to the response if needed and set Vary
101 # set the CSRF cookie
103 mg_globals
.app_config
['csrf_cookie_name'],
104 request
.environ
['CSRF_TOKEN'],
105 path
=request
.environ
['SCRIPT_NAME'],
106 domain
=mg_globals
.app_config
.get('csrf_cookie_domain'),
107 secure
=(request
.scheme
.lower() == 'https'),
110 # update the Vary header
111 response
.vary
= (getattr(response
, 'vary', None) or []) + ['Cookie']
113 def _make_token(self
, request
):
114 """Generate a new token to use for CSRF protection."""
116 return "%s" % (getrandbits(self
.CSRF_KEYLEN
),)
118 def verify_tokens(self
, request
):
119 """Verify that the CSRF Cookie exists and that it matches the
122 # confirm the cookie token was presented
123 cookie_token
= request
.cookies
.get(
124 mg_globals
.app_config
['csrf_cookie_name'],
127 if cookie_token
is None:
128 # the CSRF cookie must be present in the request
129 return HTTPForbidden()
131 # get the form token and confirm it matches
132 form
= CsrfForm(request
.POST
)
134 form_token
= form
.csrf_token
.data
136 if form_token
== cookie_token
:
137 # all's well that ends well
140 # either the tokens didn't match or the form token wasn't
141 # present; either way, the request is denied
142 return HTTPForbidden()