diff --git a/src/wtforms/csrf/core.py b/src/wtforms/csrf/core.py index 5172c77d1..f55663153 100644 --- a/src/wtforms/csrf/core.py +++ b/src/wtforms/csrf/core.py @@ -1,3 +1,5 @@ +import hmac + from wtforms.fields import HiddenField from wtforms.validators import ValidationError @@ -92,5 +94,11 @@ def validate_csrf_token(self, form, field): :param form: The form which has this CSRF token. :param field: The CSRF token field. """ - if field.current_token != field.data: + if ( + not field.current_token + or not field.data + or not hmac.compare_digest( + field.current_token.encode("utf8"), field.data.encode("utf8") + ) + ): raise ValidationError(field.gettext("Invalid CSRF Token.")) diff --git a/src/wtforms/csrf/session.py b/src/wtforms/csrf/session.py index d7ddd5b95..2a5d60c7b 100644 --- a/src/wtforms/csrf/session.py +++ b/src/wtforms/csrf/session.py @@ -68,7 +68,9 @@ def validate_csrf_token(self, form, field): check_val = (self.session["csrf"] + expires).encode("utf8") hmac_compare = hmac.new(meta.csrf_secret, check_val, digestmod=sha1) - if hmac_compare.hexdigest() != hmac_csrf: + if not hmac.compare_digest( + hmac_compare.hexdigest().encode("utf8"), hmac_csrf.encode("utf8") + ): raise ValidationError(field.gettext("CSRF failed.")) if self.time_limit: