Debian Codegraph @

docs/patterns.rst

raw
1 Security Patterns
2 =================
3
4 .. danger::
5 Be aware that starting in Flask 2.2.0, they recommend extensions store context information
6 on ``g`` which is the application context. Prior to this many extensions (including
7 Flask-Security and Flask-Login) stored things like user credential information on the
8 request context. These are now stored on ``g`` i.e. the application context. It is imperative
9 that applications not mistakenly push their own application context and forget to pop it - in that
10 case Flask won't push a new application context nor will it pop it at the end of the request - thus
11 credential information could leak from one user request to another.
12
13 Authentication and Authorization
14 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 Flask-Security provides a set of authentication decorators:
16
17 * :func:`.auth_required`
18
19 * :func:`.http_auth_required`
20
21 * :func:`.auth_token_required`
22
23 and a set of authorization decorators:
24
25 * :func:`.roles_required`
26
27 * :func:`.roles_accepted`
28
29 * :func:`.permissions_required`
30
31 * :func:`.permissions_accepted`
32
33 In addition, Flask-Login provides @login_required. In order to take advantage of all the
34 Flask-Security features, it is recommended to NOT use @login_required.
35
36 Also, if you annotate your endpoints with JUST an authorization decorator, you will never
37 get a 401 response, and (for forms) you won't be redirected to your login page. In this case
38 you will always get a 403 status code (assuming you don't override the default handlers).
39
40 While these annotations are quick and easy, it is likely that they won't completely satisfy
41 all an application's authorization requirements. A common example might be that a user can
42 only edit their own posts/documents. In cases like this - it is nice to have a uniform way
43 of handling all authorization errors. A simple way to do this is to use a special exception
44 class that you can raise either in response to Flask-Security authorization failures, or in your
45 own code. Then use Flask's ``errorhandler`` to catch that exception and create the appropriate API response::
46
47 class MyForbiddenException(Exception):
48 def __init__(self, msg='Not permitted with your privileges', status=http.HTTPStatus.FORBIDDEN):
49 self.info = {'status': status, 'msgs': [msg]}
50
51 _security = app.extensions["security"]
52
53 @_security.unauthz_handler
54 def my_unauthz_handler(func, params):
55 raise MyForbiddenException()
56
57 @app.errorhandler(MyForbiddenException)
58 def my_exception(ex):
59 return flask.jsonify(ex.info), ex.info['status']
60
61 @app.route('/doc/<int:doc_id>', methods=['PATCH'])
62 @auth_required('token', 'session')
63 def doc_patch(doc_id):
64 doc = fetch_doc(doc_id)
65 if not current_user.has_role('admin') and doc.owner != current_user:
66 raise MyForbiddenException(msg='You can only update docs you own')
67
68
69 A note about Basic Auth
70 +++++++++++++++++++++++
71 Basic Auth is supported in Flask-Security, using the @http_auth_required() decorator. If a request for an endpoint
72 protected with @http_auth_required is received, and the request doesn't contain the appropriate HTTP Headers, a 401 is returned
73 along with the required WWW-Authenticate header. In this case there won't be a usable session cookie returned so all future requests
74 will also require credentials to be sent. Effectively the caller is temporarily 'logged in' at the beginning of each request and 'logged out' again
75 at the end of the request. Most (all?) browsers intercept this response and pop up a login dialog box and remember, for the site, the entered credentials.
76 This effectively bypasses any of the normal Flask-Security login forms. By default, the Flask-Security endpoints that require the caller be
77 authenticated do NOT support ``basic`` - however the :py:data:`SECURITY_API_ENABLED_METHODS` can be used to override this.
78
79 .. _freshness_topic:
80
81 Freshness
82 ~~~~~~~~~
83 A common pattern for browser-based sites is to use sessions to manage identity. This is usually
84 implemented using session cookies. These cookies expire once the session (browser tab) is closed. This is very
85 convenient, and keeps the users from having to constantly reauthenticate. The downside is that sessions can easily be
86 open for days or weeks. This adds to the security risk that some bad-actor or XSS gets control of the browser and then can
87 do anything the user can. To mitigate that, operations that change fundamental identity characteristics (such as email, password, etc.)
88 can be protected by requiring a 'fresh' or recent authentication. Flask-Security supports this with the following:
89
90 - :func:`.auth_required` takes parameters that define how recent the authentication must have happened. In addition a grace
91 period can be specified so that multiple step operations don't require reauthentication in the middle.
92 - A default :meth:`.Security.reauthn_handler` that is called when a request fails the recent authentication check.
93 - :py:data:`SECURITY_VERIFY_URL`, :py:data:`SECURITY_US_VERIFY_URL`, :py:data:`SECURITY_WAN_VERIFY_URL`,
94 :py:data:`SECURITY_OAUTH_VERIFY_START_URL` endpoints
95 that request the user to reauthenticate.
96 - ``VerifyForm``, ``UsVerifyForm``, ``WebAuthnVerifyForm`` forms that can be extended.
97
98 Flask-Security itself uses this as part of securing the following endpoints:
99
100 - .wan_register ("/wan-register")
101 - .wan_delete ("/wan-delete")
102 - .tf_setup ("/tf-setup")
103 - .us_setup ("/us-setup")
104 - .mf_recovery_codes ("/mf-recovery-codes")
105 - .change_email ("/change-email")
106
107 using the :py:data:`SECURITY_FRESHNESS` and :py:data:`SECURITY_FRESHNESS_GRACE_PERIOD` configuration variables.
108
109 .. tip::
110 The timestamp of the users last successful authentication is stored in the session
111 as well as in the authentication token. One of these must be presented or freshness
112 will fail. You can disallow using the value in the authentication token by setting
113 :py:data:`SECURITY_FRESHNESS_ALLOW_AUTH_TOKEN` to ``False``.
114 You can disable freshness by setting ``SECURITY_FRESHNESS`` to ``timedelta(minutes=-1)``
115
116 .. _redirect_topic:
117
118 Open Redirect Exposure
119 ~~~~~~~~~~~~~~~~~~~~~~~
120 Flask-Security, accepts a ``next=xx`` parameter (either
121 as a query param OR in the POSTed form) which it will use when completing an operation
122 which results in a redirection. If a malicious user/
123 application can inject an arbitrary ``next`` parameter which redirects to an external
124 location, this results in a security vulnerability called an `open redirect`.
125 The following endpoints accept a ``next`` parameter:
126
127 - .login ("/login")
128 - .logout ("/logout")
129 - .register ("/register")
130 - .verify ("/verify")
131 - .two_factor_token_validation ("/tf-validate")
132 - .wan_verify_response ("/wan-verify")
133 - .wan_signin_response ("/wan-signin")
134 - .us_signin ("/us-signin")
135 - .us_verify ("/us-verify")
136
137 Flask-Security always quotes the path portion of a user supplied URL.
138 This `link <https://www.cve.org/CVERecord?id=CVE-2021-32618>`_ provides background of why simple parsing of URLs isn't enough.
139
140
141 .. _pass_validation_topic:
142
143 Password Validation and Complexity
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145 There is a large body of references (and endless discussions) around how to get users to create
146 good passwords. The `OWASP Authentication cheatsheet <https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html>`_
147 is a useful place to start. Flask-Security has a default password validator that:
148
149 * Checks for minimum and maximum length (minimum is configurable via :py:data:`SECURITY_PASSWORD_LENGTH_MIN`).
150 The default is 8 characters as defined by `NIST <https://pages.nist.gov/800-63-3/sp800-63b.html>`_.
151 * If :py:data:`SECURITY_PASSWORD_CHECK_BREACHED` is set, will use the API for `haveibeenpwned <https://haveibeenpwned.com>`_ to
152 check if the password is on a list of breached passwords. The configuration variable :py:data:`SECURITY_PASSWORD_BREACHED_COUNT`
153 can be used to set the minimum allowable 'breaches'.
154 * If :py:data:`SECURITY_PASSWORD_COMPLEXITY_CHECKER` is set to ``zxcvbn`` and the
155 package `zxcvbn <https://pypi.org/project/zxcvbn/>`_ is installed, it will check the password for complexity.
156
157 Be aware that ``zxcvbn`` is not actively being maintained, and has localization issues.
158
159 In addition to validation, unicode passwords should be normalized as specified
160 by NIST requirement: `5.1.1.2 Memorized Secret Verifiers`_. Normalization can
161 be disabled by setting the :py:data:`SECURITY_PASSWORD_NORMALIZE_FORM` to ``None``.
162 Validation and normalization is encapsulated in :class:`.PasswordUtil`.
163 This can be overridden by passing your class at app initialization time.
164 The :meth:`.PasswordUtil.validate` is passed additional kwargs to allow custom
165 validators more flexibility.
166 A custom validator can still call the underlying methods where appropriate:
167 :func:`flask_security.password_length_validator`, :func:`flask_security.password_complexity_validator`,
168 and :func:`flask_security.password_breached_validator`.
169
170 .. _5.1.1.2 Memorized Secret Verifiers: https://pages.nist.gov/800-63-3/sp800-63b.html#sec5
171
172
173 .. _generic_responses:
174
175 Generic Responses - Avoiding User Enumeration
176 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
177 How an application responds to API requests that contain identity or authentication information
178 can give would-be attackers insight into active users on the system. OWASP has a great `cheat-sheet`_ describing
179 this and useful ways to avoid it. Flask-Security supports this by setting the
180 :py:data:`SECURITY_RETURN_GENERIC_RESPONSES` configuration to ``True``. As documented in the cheat-sheet - this does
181 come with some usability concerns. The following endpoints are affected:
182
183 * :py:data:`SECURITY_REGISTER_URL` - The same response will be returned whether the email (or username) is already in the
184 system or not. JSON requests will ALWAYS return 200. If :py:data:`SECURITY_CONFIRMABLE` is set (it should be!), the
185 `SECURITY_MSG_CONFIRM_REGISTRATION` message will be flashed for both new and existing email addresses. Detailed errors will still
186 be returned for things like insufficient password complexity, etc.. In the case of trying to register an existing email, an email will be sent to that email address
187 explaining that they are already registered and displaying the associated username (if any) and provide a hint on how to reset their
188 password if they forgot it. In the case of a new email but an already registered username, an email will be sent saying that the
189 user must try registering again with a different username.
190 * :py:data:`SECURITY_LOGIN_URL` - For any errors (unknown username, inactive account, bad password) the `SECURITY_MSG_GENERIC_AUTHN_FAILED`
191 message will be returned.
192 * :py:data:`SECURITY_RESET_URL` - In all cases the `SECURITY_MSG_PASSWORD_RESET_REQUEST` message will be flashed. For JSON
193 a 200 will always be returned (whether an email was sent or not).
194 ``Note``: If the application overrides the form and adds an additional field (e.g. `captcha`) and that field has
195 a validation error, a normal form error response will be returned (and JSON will return a 400).
196 * :py:data:`SECURITY_CONFIRM_URL` - In all cases the `SECURITY_MSG_CONFIRMATION_REQUEST` message will be flashed. For JSON
197 a 200 will always be returned (whether an email was sent or not).
198 ``Note``: If the application overrides the form and adds an additional field (e.g. `captcha`) and that field has
199 a validation error, a normal form error response will be returned (and JSON will return a 400).
200 * :py:data:`SECURITY_US_SIGNIN_SEND_CODE_URL` - The `SECURITY_MSG_GENERIC_US_SIGNIN` message will be flashed in all cases -
201 whether a selected method is setup for the user or not.
202 * :py:data:`SECURITY_US_SIGNIN_URL` - For any errors (unknown username, inactive account, bad passcode) the `SECURITY_MSG_GENERIC_AUTHN_FAILED`
203 message will be returned.
204 * :py:data:`SECURITY_US_VERIFY_LINK_URL` - For any errors (unknown username, inactive account, bad passcode) the `SECURITY_MSG_GENERIC_AUTHN_FAILED`
205 message will be returned.
206
207
208 In the case of an application using a ``username`` as an identity it should be noted that it is possible for a bad-actor to enumerate usernames, albeit slowly,
209 by parsing emails.
210
211 Note also that :py:data:`SECURITY_REQUIRES_CONFIRMATION_ERROR_VIEW` is ignored in these cases. If your application is using WebAuthn, be sure
212 to set :py:data:`SECURITY_WAN_ALLOW_USER_HINTS` to ``False``.
213
214
215 .. _cheat-sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#authentication-and-error-messages
216
217 .. _csrf_topic:
218
219 CSRF
220 ~~~~
221 By default, Flask-Security, via Flask-WTForms protects all form based POSTS
222 from CSRF attacks using well vetted per-session hidden-form-field csrf-tokens.
223
224 Any web application that relies on session cookies for authentication must have CSRF protection.
225 For more details please read this `OWASP CSRF cheatsheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md>`_.
226 A couple important take-aways - first - it isn't about forms versus JSON - it is about
227 how the API is authenticated (session cookies versus authentication token). Second there is the
228 concern about 'login CSRF' - is protection needed prior to authentication (yes if
229 you have a really secure/popular site).
230
231 Flask-Security strives to support various options for both its endpoints (e.g. ``/login``)
232 and the application endpoints (protected with Flask-Security decorators such as :func:`.auth_required`).
233
234 If your application just uses forms that are derived from ``Flask-WTF::Flaskform`` - you are done.
235 Note that all of Flask-Security's endpoints are form based (regardless of how the request was made).
236
237 Behind-The-Scenes
238 ++++++++++++++++++
239 Depending on configuration, there are 3 places CSRF tokens can be checked:
240 #) As part of form validation for any form derived from FlaskForm (which all Flask-Security
241 forms are). An error here is recorded in the ``csrf_token`` field and the calling view
242 decides whether to return 200 or 400.
243 This is the default if no other configuration changes are made.
244 #) As part of an @before_request handler that Flask-WTF sets up if CSRFprotect() is called. On error
245 this always returns HTTP 400 and small snippet of HTML. This can be disabled
246 by setting config["WTF_CSRF_CHECK_DEFAULT"] = False.
247 #) As part of a Flask-Security decorator (:func:`.unauth_csrf`, :func:`.auth_required`). On
248 error either a JSON response is returned OR CSRFError exception is raised and 400 is returned with the small snippet of HTML
249 (the exception and default response is part of Flask-WTF).
250
251 CSRF: Single-Page-Applications and AJAX/XHR
252 ++++++++++++++++++++++++++++++++++++++++++++
253 If you are thinking about using authentication tokens in your browser-based UI - read
254 `this article <https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage>`_
255 on how and where to store authentication tokens. While the
256 article is talking about JWT it applies to Flask-Security tokens as well.
257
258 In general, it is considered more secure (and easier) to use sessions for browser
259 based UI, and tokens for service to service and scripts.
260
261 For SPA, and especially those that aren't served via your flask application, there are difficulties
262 with actually retrieving and using a CSRF token. There are 2 normal ways to do this:
263
264 * Have the csrf-token available via a JSON GET request that can be attached as a
265 header in every mutating request.
266 * Have a cookie that can be read via JavaScript whose value is the csrf-token that
267 can be attached as a header in every mutating request.
268
269 Flask-Security supports both solutions.
270
271 Explicit fetch and send of csrf-token
272 --------------------------------------
273 The current session CSRF token
274 is returned on every JSON GET request (to a Flask-Security endpoint) as ``response['csrf_token`]``.
275 For web applications that ARE served via flask, it is even easier to get the csrf-token -
276 `<https://flask-wtf.readthedocs.io/en/1.2.x/csrf/>`_ gives some useful tips.
277
278 Armed with the csrf-token, the UI must include that in every mutating operation.
279 Be careful NOT to include the csrf-token in non-mutating requests (such as GETs).
280 If your application uses GET to actually modify state - please stop.
281
282 An example using `axios <https://github.com/axios/axios>`_ ::
283
284
285 # This will fetch the csrf-token. Note that we do a GET on the login endpoint
286 # which will get us the csrf-token even though we aren't yet logged in.
287 # Note further the 'data: null' and explicit Content-Type header - these are
288 # critical, otherwise Flask-Security will return the login form.
289 axios.get('/login',{data: null, headers: {'Content-Type': 'application/json'}}).then(function (resp) {
290 csrf_token = resp.data['response']['csrf_token']
291 })
292
293
294 # This will add the token header to each outgoing mutating request.
295 axios.interceptors.request.use(function (config) {
296 if (["post", "delete", "patch", "put"].includes(config["method"])) {
297 if (csrf_token !== '') {
298 config.headers["X-CSRF-Token"] = csrf_token
299 }
300 }
301 return config;
302 }, function (error) {
303 // Do something with request error
304 return Promise.reject(error);
305 });
306
307
308
309 Note that we use the header name ``X-CSRF-Token`` as that is one of the default
310 headers configured in Flask-WTF (*WTF_CSRF_HEADERS*)
311
312 To protect your application's endpoints (that presumably are not using Flask forms),
313 you need to enable CSRF as described in the FlaskWTF `documentation <https://flask-wtf.readthedocs.io/en/1.2.x/csrf/>`_: ::
314
315 flask_wtf.CSRFProtect(app)
316
317 This will turn on CSRF protection on ALL endpoints, including Flask-Security. This protection differs slightly from
318 the default that is part of FlaskForm in that it will first look at the request body and see if it can find a form field that contains
319 the csrf-token, and if it can't, it will check if the request has a header that is listed in *WTF_CSRF_HEADERS* and use that.
320 Be aware that if you enable this it will ONLY work if you send the session cookie on each request.
321
322 .. note::
323 It is IMPORTANT that you initialize/call ``CSRFProtect`` PRIOR to initializing Flask_Security.
324
325 .. note::
326 Calling CSRFProtect(app) will setup a @before_request handler to verify CSRF - this occurs BEFORE any Flask-Security decorators
327 or other view/form logic. One side effect is that CSRFProtect, on error, will raise a BadRequest error which returns a small
328 piece of HTML by default - your application will need to add a Flask ErrorHandler to change that. Alternatively, and recommended
329 is to set `WTF_CSRF_CHECK_DEFAULT` to `False` - which will disable the @before_request and let Flask-Security handle CSRF protection
330 including properly returning a JSON response if the caller asks for it.
331
332 .. danger::
333 If you set `WTF_CSRF_CHECK_DEFAULT` to `False` this will turn off CSRF checking for all your endpoints unless they are protected with
334 @auth_required() or have explicit CSRF checking.
335
336
337 Using a Cookie
338 --------------
339 You can instruct Flask-Security to send a cookie that contains the csrf token.
340 The cookie will be set on a call to ``GET /login`` or ``GET /us-signin`` - as well as after a successful authentication.
341 This can be very convenient since various JavaScript AJAX packages are pre-configured to extract the contents of a cookie
342 and send it on every mutating request as an HTTP header. `axios`_ for example has a default configuration
343 that it will look for a cookie named ``XSRF-TOKEN`` and will send the contents of that back
344 in an HTTP header called ``X-XSRF-Token``. This means that if you use that package you don't need to make
345 any changes to your UI and just need the following configuration::
346
347 # Have cookie sent
348 app.config["SECURITY_CSRF_COOKIE_NAME"] = "XSRF-TOKEN"
349
350 # Don't have csrf tokens expire (they are invalid after logout)
351 app.config["WTF_CSRF_TIME_LIMIT"] = None
352
353 # Enable CSRF protection
354 flask_wtf.CSRFProtect(app)
355
356 Angular's `httpClient`_ also supports this.
357
358 For React based projects you are free to choose your http client (`fetch` is bundled by default). Retrieving the token is easy::
359
360 fetch(url, {
361 credentials: 'include',
362 mode: 'cors',
363 headers: {
364 'Accept': 'application/json',
365 'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN')
366 }
367 });
368
369 Sending the token on every mutating request is something that you should implement yourself. As an example an API call to an API
370 endpoint that does CSRF validation::
371
372 function addUser(details) {
373 return fetch('https://api.example.com/user', {
374 mode: 'cors',
375 method: 'POST',
376 credentials: 'include',
377 body: JSON.stringify(details),
378 headers: {
379 'Content-Type': 'application/json',
380 'Accept': 'application/json',
381 'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN')
382 }
383 }).then(response => {
384 return response.json().then(data => {
385 if (response.ok) {
386 return data;
387 } else {
388 return Promise.reject({status: response.status, data});
389 }
390 });
391 });
392 }
393
394 When you have axios setup correctly, this is a lot easier::
395
396 function addUser(details) {
397 return axios.post('https://api.example.com/user', details);
398 }
399
400
401 CSRF: Enable protection for session auth, but not token auth
402 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
403 As mentioned above, CSRF is critical for any mutating operation where the authentication credentials are 'invisibly' sent - such as a session cookie -
404 from a browser. But if your endpoint a) can only be authenticated with an attached token or b) can be called either via session OR token;
405 it is often desirable not to force token API users to deal with CSRF. To solve this, we need to keep CSRFProtect from checking the csrf-token early in the
406 request and instead defer that decision to later decorators/code. Flask-Security's authentication decorators (:func:`.auth_required`,
407 :func:`.auth_token_required`, and :func:`.http_auth_required` all support calling csrf protection based on configuration::
408
409 # Disable pre-request CSRF
410 app.config["WTF_CSRF_CHECK_DEFAULT"] = False
411
412 # Check csrf for session and http auth (but not token)
413 app.config["SECURITY_CSRF_PROTECT_MECHANISMS"] = ["session", "basic"]
414
415 # Enable CSRF protection
416 flask_wtf.CSRFProtect(app)
417
418 @app.route("/")
419 @auth_required("token", "session")
420 def home_page():
421
422 With this configuration, CSRF won't be required if the caller uses an authentication token, but if it uses
423 the session cookie it will.
424
425 CSRF: Pro-Tips
426 ++++++++++++++
427 #) Be aware that for CSRF to work, callers MUST send the session cookie. So
428 for pure API (token based), and no session cookie - there is no way to support 'login CSRF'.
429 So your app must set :py:data:`SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS`
430 (or clients must use CSRF/session cookie for logging
431 in then once they have an authentication token, no further need for cookie).
432
433 #) If you enable CSRFProtect(app) and you want to send request data as JSON,
434 then you must include the CSRF token in the header (e.g. X-CSRF-Token)
435
436 #) You must enable CSRFProtect(app) if you want to accept the CSRF token in the request
437 header.
438
439 #) Annotate each of your endpoints with a @auth_required decorator (and don't rely
440 on just a @role_required or @login_required decorator) so that Flask-Security
441 gets control at the appropriate place.
442
443 #) If you can't use a decorator, Flask-Security exposes the underlying method
444 :func:`flask_security.handle_csrf`.
445
446 #) Consider starting by setting :py:data:`SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS` to True. Your
447 application likely doesn't need 'login CSRF' protection, and it is frustrating
448 to not even be able to login via API!
449
450 #) If you have unauthenticated endpoints that you want to protect with CSRF then
451 use the :func:`flask_security.unauth_csrf` decorator.
452
453
454 .. _axios: https://github.com/axios/axios
455 .. _httpClient: https://angular.io/guide/http#security-xsrf-protection