csrf.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # GNU MediaGoblin -- federated, autonomous media hosting
  2. # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
  3. #
  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.
  8. #
  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.
  13. #
  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/>.
  16. import random
  17. import logging
  18. from werkzeug.exceptions import Forbidden
  19. from wtforms import Form, HiddenField, validators
  20. from mediagoblin import mg_globals
  21. from mediagoblin.meddleware import BaseMeddleware
  22. from mediagoblin.tools.translate import lazy_pass_to_ugettext as _
  23. _log = logging.getLogger(__name__)
  24. # Use the system (hardware-based) random number generator if it exists.
  25. # -- this optimization is lifted from Django
  26. if hasattr(random, 'SystemRandom'):
  27. getrandbits = random.SystemRandom().getrandbits
  28. else:
  29. getrandbits = random.getrandbits
  30. def csrf_exempt(func):
  31. """Decorate a Controller to exempt it from CSRF protection."""
  32. func.csrf_enabled = False
  33. return func
  34. class CsrfForm(Form):
  35. """Simple form to handle rendering a CSRF token and confirming it
  36. is included in the POST."""
  37. csrf_token = HiddenField("",
  38. [validators.InputRequired()])
  39. def render_csrf_form_token(request):
  40. """Render the CSRF token in a format suitable for inclusion in a
  41. form."""
  42. if 'CSRF_TOKEN' not in request.environ:
  43. return None
  44. form = CsrfForm(csrf_token=request.environ['CSRF_TOKEN'])
  45. return form.csrf_token
  46. class CsrfMeddleware(BaseMeddleware):
  47. """CSRF Protection Meddleware
  48. Adds a CSRF Cookie to responses and verifies that it is present
  49. and matches the form token for non-safe requests.
  50. """
  51. CSRF_KEYLEN = 64
  52. SAFE_HTTP_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
  53. def process_request(self, request, controller):
  54. """For non-safe requests, confirm that the tokens are present
  55. and match.
  56. """
  57. # get the token from the cookie
  58. try:
  59. request.environ['CSRF_TOKEN'] = \
  60. request.cookies[mg_globals.app_config['csrf_cookie_name']]
  61. except KeyError:
  62. # if it doesn't exist, make a new one
  63. request.environ['CSRF_TOKEN'] = self._make_token(request)
  64. # if this is a non-"safe" request (ie, one that could have
  65. # side effects), confirm that the CSRF tokens are present and
  66. # valid
  67. if (getattr(controller, 'csrf_enabled', True) and
  68. request.method not in self.SAFE_HTTP_METHODS and
  69. ('gmg.verify_csrf' in request.environ or
  70. 'paste.testing' not in request.environ)
  71. ):
  72. return self.verify_tokens(request)
  73. def process_response(self, request, response):
  74. """Add the CSRF cookie to the response if needed and set Vary
  75. headers.
  76. """
  77. # set the CSRF cookie
  78. response.set_cookie(
  79. mg_globals.app_config['csrf_cookie_name'],
  80. request.environ['CSRF_TOKEN'],
  81. path=request.environ['SCRIPT_NAME'],
  82. domain=mg_globals.app_config.get('csrf_cookie_domain'),
  83. secure=(request.scheme.lower() == 'https'),
  84. httponly=True)
  85. # update the Vary header
  86. response.vary = list(getattr(response, 'vary', None) or []) + ['Cookie']
  87. def _make_token(self, request):
  88. """Generate a new token to use for CSRF protection."""
  89. return "%s" % (getrandbits(self.CSRF_KEYLEN),)
  90. def verify_tokens(self, request):
  91. """Verify that the CSRF Cookie exists and that it matches the
  92. form value."""
  93. # confirm the cookie token was presented
  94. cookie_token = request.cookies.get(
  95. mg_globals.app_config['csrf_cookie_name'],
  96. None)
  97. if cookie_token is None:
  98. # the CSRF cookie must be present in the request, if not a
  99. # cookie blocker might be in action (in the best case)
  100. _log.error('CSRF cookie not present')
  101. raise Forbidden(_('CSRF cookie not present. This is most likely '
  102. 'the result of a cookie blocker or somesuch.<br/>'
  103. 'Make sure to permit the settings of cookies for '
  104. 'this domain.'))
  105. # get the form token and confirm it matches
  106. form = CsrfForm(request.form)
  107. if form.validate():
  108. form_token = form.csrf_token.data
  109. if form_token == cookie_token:
  110. # all's well that ends well
  111. return
  112. # either the tokens didn't match or the form token wasn't
  113. # present; either way, the request is denied
  114. errstr = 'CSRF validation failed'
  115. _log.error(errstr)
  116. raise Forbidden(errstr)