SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
CSRF vulnerabilities have been found in large and popular sites such as YouTube. These attacks are problematic because the mechanism they use is relatively easy to exploit. This extension attempts to aid you in securing your application from such attacks.
This extension is based on the excellent Django middleware.
Installation
Install the extension with one of the following commands:
or alternatively if you have pip installed:
Usage
Using SeaSurf is fairly straightforward. Begin by importing the extension and then passing your application object back to the extension, like this:
This extension is configurable via a set of configuration variables which can be added to the Flask app’s config file:
- CSRF_COOKIE_NAME for the cookie name
- CSRF_COOKIE_TIMEOUT for the cookie timeout
- CSRF_COOKIE_HTTPONLY for setting the cookie HTTPOnly flag
- CSRF_COOKIE_SECURE for setting the cookie secure flag
- CSRF_COOKIE_PATH for setting the cookie path
- CSRF_COOKIE_DOMAIN for setting the cookie domain
- CSRF_DISABLE to disable CSRF prevention
Except for the last option, all values are passed verbatim to the Response.set_cookiemethod.
Corresponding code will need to be added to the templates where POST, PUT, and DELETE HTTP methods are anticipated. In the case of POST requests a hidden field should be added, something like this:
The extension adds a global function to the Jinja template engine called csrf_token. This is a function that retrieves the current token and will be matched against the request token.
By default all requests that are not GET, HEAD, OPTIONS, or TRACE are validated against the CSRF token sent by the client and as rendered on the page. However a view may be completely exempted from validation using the exempt decorator. For instance it’s possible to decorate a view as shown below:
By default when a request is determined to be secure, i.e. using HTTPS, then we use strict referer checking to prevent a man-in-the-middle attack from being plausible. To disable checking the Referer header, set the Flask app’s configCSRF_CHECK_REFERER to False.
Note
- Setting
TESTING = True
in config will disable the token generation! - If you are getting
None
as token check ifTESTING = True
in config.
AJAX Usage
AJAX is not exempted from CSRF validation as it is a plausible vector for cross-site request forgery. As such, POSTing with AJAX can make use of the aforementioned method, but other HTTP methods, such as PUT and DELETE might be better suited to using the X-CSRFToken header instead.
Essentially this header is passed back to the backend by way of extracting the token from the cookie using JavaScript. For a better explanation of how this might be done please refer to the Django CSRF documentation.
Flask-WTForms Usage
If you would like to use Flask-Seasurf with a form generator, such as WTForms, it is possible to do so. Below is a simple example.
First we will define a custom SeaSurfForm object in a seasurf_form module like so:
Now assume we define a module forms as such:
This is the basis of our login form which we will serve up in a view to the user. Finally we can use this in our template login.html:
API
- class
flask_seasurf.
SeaSurf
(app=None) - Primary class container for CSRF validation logic. The main function of this extension is to generate and validate CSRF tokens. The design and implementation of this extension is influenced by Django’s CSRF middleware.Tokens are generated using a salted SHA1 hash. The salt is based off a a random range. The OS’s SystemRandom is used if available, otherwise the core random.randrange is used.Then pass the application object to be configured:Validation will now be active for all requests whose methods are not GET, HEAD, OPTIONS, or TRACE.When using other request methods, such as POST for instance, you will need to provide the CSRF token as a parameter. This can be achieved by making use of the Jinja global. In your template:This will assign a token to both the session cookie and the rendered HTML which will then be validated on the backend. POST requests missing this field will fail unless the header X-CSRFToken is specified.Excluding Views From ValidationFor views that use methods which may be validated but for which you wish to not run validation on you may make use of the
exempt
decorator to indicate that they should not be checked.- A decorator to programmatically disable setting the CSRF token cookie on the response. The function will be passed a Flask Response object for the current request.The decorated function must return
True
orFalse
.
exempt
(view)- A decorator that can be used to exclude a view from CSRF validation.
Parameters: view – The view to be wrapped by the decorator.
include
(view)- A decorator that can be used to include a view from CSRF validation.
Parameters: view – The view to be wrapped by the decorator.
init_app
(app)- Initializes a Flask object app, binds CSRF validation to app.before_request, and assigns csrf_token as a Jinja global.
Parameters: app – The Flask application object.
validate
()- Validates a CSRF token for the current request.If CSRF token is invalid, stops execution and sends a Forbidden error response to the client. Can be used in combination with
exempt
to programmatically enable CSRF protection per request.
Tidak ada komentar:
Posting Komentar