1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 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 werkzeug
.exceptions
import Forbidden
21 from wtforms
import Form
, HiddenField
, validators
23 from mediagoblin
import mg_globals
24 from mediagoblin
.meddleware
import BaseMeddleware
25 from mediagoblin
.tools
.translate
import lazy_pass_to_ugettext
as _
27 _log
= logging
.getLogger(__name__
)
29 # Use the system (hardware-based) random number generator if it exists.
30 # -- this optimization is lifted from Django
31 if hasattr(random
, 'SystemRandom'):
32 getrandbits
= random
.SystemRandom().getrandbits
34 getrandbits
= random
.getrandbits
37 def csrf_exempt(func
):
38 """Decorate a Controller to exempt it from CSRF protection."""
40 func
.csrf_enabled
= False
45 """Simple form to handle rendering a CSRF token and confirming it
46 is included in the POST."""
48 csrf_token
= HiddenField("",
49 [validators
.InputRequired()])
52 def render_csrf_form_token(request
):
53 """Render the CSRF token in a format suitable for inclusion in a
56 if 'CSRF_TOKEN' not in request
.environ
:
59 form
= CsrfForm(csrf_token
=request
.environ
['CSRF_TOKEN'])
61 return form
.csrf_token
64 class CsrfMeddleware(BaseMeddleware
):
65 """CSRF Protection Meddleware
67 Adds a CSRF Cookie to responses and verifies that it is present
68 and matches the form token for non-safe requests.
72 SAFE_HTTP_METHODS
= ("GET", "HEAD", "OPTIONS", "TRACE")
74 def process_request(self
, request
, controller
):
75 """For non-safe requests, confirm that the tokens are present
79 # get the token from the cookie
81 request
.environ
['CSRF_TOKEN'] = \
82 request
.cookies
[mg_globals
.app_config
['csrf_cookie_name']]
85 # if it doesn't exist, make a new one
86 request
.environ
['CSRF_TOKEN'] = self
._make
_token
(request
)
88 # if this is a non-"safe" request (ie, one that could have
89 # side effects), confirm that the CSRF tokens are present and
91 if (getattr(controller
, 'csrf_enabled', True) and
92 request
.method
not in self
.SAFE_HTTP_METHODS
and
93 ('gmg.verify_csrf' in request
.environ
or
94 'paste.testing' not in request
.environ
)
97 return self
.verify_tokens(request
)
99 def process_response(self
, request
, response
):
100 """Add the CSRF cookie to the response if needed and set Vary
104 # set the CSRF cookie
106 mg_globals
.app_config
['csrf_cookie_name'],
107 request
.environ
['CSRF_TOKEN'],
108 path
=request
.environ
['SCRIPT_NAME'],
109 domain
=mg_globals
.app_config
.get('csrf_cookie_domain'),
110 secure
=(request
.scheme
.lower() == 'https'),
113 # update the Vary header
114 response
.vary
= list(getattr(response
, 'vary', None) or []) + ['Cookie']
116 def _make_token(self
, request
):
117 """Generate a new token to use for CSRF protection."""
119 return "%s" % (getrandbits(self
.CSRF_KEYLEN
),)
121 def verify_tokens(self
, request
):
122 """Verify that the CSRF Cookie exists and that it matches the
125 # confirm the cookie token was presented
126 cookie_token
= request
.cookies
.get(
127 mg_globals
.app_config
['csrf_cookie_name'],
130 if cookie_token
is None:
131 # the CSRF cookie must be present in the request, if not a
132 # cookie blocker might be in action (in the best case)
133 _log
.error('CSRF cookie not present')
134 raise Forbidden(_('CSRF cookie not present. This is most likely '
135 'the result of a cookie blocker or somesuch.<br/>'
136 'Make sure to permit the settings of cookies for '
139 # get the form token and confirm it matches
140 form
= CsrfForm(request
.form
)
142 form_token
= form
.csrf_token
.data
144 if form_token
== cookie_token
:
145 # all's well that ends well
148 # either the tokens didn't match or the form token wasn't
149 # present; either way, the request is denied
150 errstr
= 'CSRF validation failed'
152 raise Forbidden(errstr
)