🔒️ Protect against CSRF attacks (#5)
* 🔒️ Protect against CSRF attacks CORS and the JSON API heavily reduced the attack surface here, but especially the upload endpoints were still vulnerable to CSRF attacks. All endpoints on the API that use methods beyond GET, HEAD or OPTIONS now require the presence of a csrf token (generated by the UI on first load) AND a X-CSRF-Token header with a matching value (Double Submit Cookie), unless authorization is done through an API-Key instead of a browser session. Additionally, the SameSite attribute now is set to "Strict" by default. * 🔒️ Expand CSRF protection to plugins Plugins are currently by default *opted out* of CSRF protection, to ensure backwards compatibility with third party plugins in the field. However, in a future OctoPrint version this will become a default *opt in*. Plugin authors are advised to adjust the implementation with an explicit decision via a logged warning generated in the default implementation. Additionally, plugins that have opted out their whole plugin will generate a warning in the startup messages. A decorator to exempt individual endpoints from CSRF protection as certain workflows require (see for example the auth request in the appkeys plugin) is provided. The general rule of thumb should be to opt in and only exempt those non GET/HEAD/OPTIONS endpoints that really need to be usable without an API key or CSRF cookie/header combo. In practice, that should be pretty much non. * 🐛 Fix a left-over from a local test * 🐛 Fix wrong setting in E2E test config.yaml * 🧑💻 Set CSRF header for $.ajax as well We already ensure the header is set in the client lib and on the file upload widgets, but many third party plugins don't use the client lib but rather $.ajax directly and thus break without this. * 📝 Improve docs on CSRF protection
This commit is contained in:
1 parent
0db80dc0c9
commit
59a0c8e8d7
22 files changed
+402
-20
No files matched your search
@@ -2,6 +2,7 @@ accessControl:
|
||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||
devel:
|
||||
enableRateLimiter: false
|
||||
enableCsrfProtection: false
|
||||
plugins:
|
||||
virtual_printer:
|
||||
enabled: true
|
||||
|
||||
+24
-1
@@ -135,7 +135,7 @@ check the corresponding checkbox in the API settings dialog.
|
||||
|
||||
.. warning::
|
||||
|
||||
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
|
||||
This means any browser page can send requests to the OctoPrint API. Authorization via an API-Key is still required however.
|
||||
|
||||
If CORS is not enabled you will get errors like the following::
|
||||
|
||||
@@ -151,6 +151,29 @@ If CORS is not enabled you will get errors like the following::
|
||||
the login mechanism (or reusing an existing login session). When accessing OctoPrint
|
||||
via CORS, you'll therefore always need to use an API key.
|
||||
|
||||
.. _sec-api-general-csrf:
|
||||
|
||||
CSRF Protection
|
||||
===============
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
|
||||
To protect OctoPrint against `CSRF attacks <https://owasp.org/www-community/attacks/csrf>`_ against the non CORS affected upload endpoints, in case of browser session based authorization the API
|
||||
is protected using the `Double Submit Cookie mitigation strategy <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie>`_.
|
||||
On first page load of the UI, the login page or the recovery page, a ``csrf_token_P<port>`` or ``csrf_token_P<port>_R<root>`` cookie is set
|
||||
that can be read via client-side JavaScript. All requests towards the API that are not ``GET``, ``HEAD`` or ``OPTIONS``
|
||||
and rely on cookie based authorization (so not on an API key but rather an active login session) are required
|
||||
to send both the ``csrf_token`` cookie as well as an ``X-CSRF-Token`` header containing its value.
|
||||
|
||||
.. note::
|
||||
|
||||
If you use the :ref:`JS Client library <sec-jsclientlib>`, this will take care of doing the needful for you. Any code in the *Core UI* calling
|
||||
API functions through ``$.ajax`` or ``$.get`` or ``$.post`` will also take care of this for you. If you use another library for
|
||||
accessing OctoPrint's API in a browser context, you'll need to make sure to send the ``X-CSRF-Token`` header yourself. Examples for
|
||||
several JS frameworks can be found in the `OWASP cheatsheet on CSRF attacks <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#javascript-guidance-for-auto-inclusion-of-csrf-tokens-as-an-ajax-request-header>`_.
|
||||
Take a look at the implementations of ``OctoPrintClient.getCookie`` and ``OctoPrintClient.getHeaders`` in ``src/octoprint/static/js/client/base.js``
|
||||
for details on how to retrieve the cookie value and how to construct the header.
|
||||
|
||||
.. _sec-api-general-login:
|
||||
|
||||
Login
|
||||
|
||||
@@ -74,15 +74,39 @@
|
||||
|
||||
:returns string: The base url to use to access OctoPrint's API.
|
||||
|
||||
.. js:function:: OctoPrintClient.getRequestHeaders(additional)
|
||||
.. js:function:: OctoPrintClient.getCookie(name)
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
|
||||
Returns the value of the cookie with name ``name``. The port based cookie suffix and if
|
||||
necessary also the script root based suffix will be automatically applied to the ``name``
|
||||
prior to looking up the value.
|
||||
|
||||
:return string: The value of the cookie, if set & accessible, else an empty string.
|
||||
|
||||
.. js:function:: OctoPrintClient.getRequestHeaders(method, additional, opts)
|
||||
|
||||
.. versionchanged:: 1.8.3
|
||||
|
||||
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
|
||||
necessary headers and any additionally provided ones.
|
||||
|
||||
At the moment this entails setting the ``X-Api-Key`` header based on the current value of
|
||||
``OctoPrint.options.apikey`` at a minimum.
|
||||
``OctoPrint.options.apikey``, if set. Otherwise, for non-cross-domain requests targeting
|
||||
methods other than ``GET``, ``HEAD`` or ``OPTIONS``, the current CSRF token is read from the
|
||||
associated cookie and set as ``X-CSRF-Token``.
|
||||
|
||||
:param object additional: Additional headers to add to the request.
|
||||
.. note::
|
||||
|
||||
Up until OctoPrint 1.8.3, this method's signature consisted only of the ``additional``
|
||||
parameter. It has been changed in a backward compatible way so that calling it with the
|
||||
first parameter being the set of additional headers will still work. This mode of operation
|
||||
is deprecated however and will be removed in a future version.
|
||||
A warning will be logged to the debug console accordingly.
|
||||
|
||||
:param str method: Method of the request for which to set headers
|
||||
:param object additional: Additional headers to add to the request, optional.
|
||||
:param object opts: Additional opts passed to the request, used to read cross domain setting, optional.
|
||||
:returns object: HTTP headers to use for requests.
|
||||
|
||||
.. js:function:: OctoPrintClient.ajax(method, url, opts)
|
||||
|
||||
@@ -1352,8 +1352,39 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
||||
|
||||
.. warning::
|
||||
|
||||
As of OctoPrint 1.8.3, endpoints provided through a ``BlueprintPlugin`` do **not** automatically fall under
|
||||
OctoPrint's :ref:`CSRF protection <sec-api-general-csrf>`, for reasons of backwards compatibility. There will be a short grace period before this changes. You
|
||||
can and should however already opt into CSRF protection for your endpoints by implementing ``is_blueprint_csrf_protected``
|
||||
and returning ``True`` from it. You can exempt certain endpoints from CSRF protection by decorating them with
|
||||
``@octoprint.plugin.BlueprintPlugin.csrf_exempt``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPlugin(octoprint.plugin.BlueprintPlugin):
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_world", methods=["GET"])
|
||||
def hello_world(self):
|
||||
# This is a GET request and thus not subject to CSRF protection
|
||||
return "Hello world!"
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_you", methods=["POST"])
|
||||
def hello_you(self):
|
||||
# This is a POST request and thus subject to CSRF protection. It is not exempt.
|
||||
return "Hello you!"
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hello_me", methods=["POST"])
|
||||
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||
def hello_me(self):
|
||||
# This is a POST request and thus subject to CSRF protection, but this one is exempt.
|
||||
return "Hello me!"
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||
|
||||
.. versionchanged:: 1.8.3
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -1372,7 +1403,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
def decorator(f):
|
||||
# We attach the decorator parameters directly to the function object, because that's the only place
|
||||
# we can access right now.
|
||||
# This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
||||
# This neat little trick was adapted from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
|
||||
if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None:
|
||||
f._blueprint_rules = defaultdict(list)
|
||||
f._blueprint_rules[f.__name__].append((rule, options))
|
||||
@@ -1405,6 +1436,27 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def csrf_exempt():
|
||||
"""
|
||||
A decorator to mark a view method in your BlueprintPlugin as exempt from :ref:`CSRF protection <sec-api-general-csrf>`. This makes sense
|
||||
if you offer an authenticated API for a certain workflow (see e.g. the bundled appkeys plugin) but in most
|
||||
cases should not be needed.
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
"""
|
||||
|
||||
def decorator(f):
|
||||
if (
|
||||
not hasattr(f, "_blueprint_csrf_exempt")
|
||||
or f._blueprint_csrf_exempt is None
|
||||
):
|
||||
f._blueprint_csrf_exempt = set()
|
||||
f._blueprint_csrf_exempt.add(f.__name__)
|
||||
return f
|
||||
|
||||
return decorator
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
@@ -1422,6 +1474,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
import flask
|
||||
|
||||
from octoprint.server.util.csrf import add_exempt_view
|
||||
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs)
|
||||
|
||||
@@ -1435,9 +1489,14 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(
|
||||
rule, options.pop("endpoint", f.__name__), view_func=f, **options
|
||||
)
|
||||
endpoint = options.pop("endpoint", f.__name__)
|
||||
blueprint.add_url_rule(rule, endpoint, view_func=f, **options)
|
||||
|
||||
if (
|
||||
hasattr(f, "_blueprint_csrf_exempt")
|
||||
and member in f._blueprint_csrf_exempt
|
||||
):
|
||||
add_exempt_view(f"plugin.{self._identifier}.{endpoint}")
|
||||
|
||||
if (
|
||||
hasattr(f, "_blueprint_error_handler")
|
||||
@@ -1486,6 +1545,29 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
"""
|
||||
return True
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_csrf_protected(self):
|
||||
"""
|
||||
Whether a blueprint's endpoints are :ref:`CSRF protected <sec-api-general-csrf>`. For now, this defaults to ``False`` to leave it up to
|
||||
plugins to decide which endpoints *should* be protected. Long term, this will default to ``True`` and hence
|
||||
enforce protection unless a plugin opts out by returning False here.
|
||||
|
||||
If you do not override this method in your mixin implementation, a warning will be logged to the console
|
||||
to alert you of the requirement to make a decision here and to not rely on the default implementation, due to the
|
||||
forthcoming change in implemented default behaviour.
|
||||
|
||||
.. versionadded:: 1.8.3
|
||||
"""
|
||||
self._logger.warning(
|
||||
"The Blueprint of this plugin is relying on the default implementation of "
|
||||
"is_blueprint_csrf_protected (newly added in OctoPrint 1.8.3), which in a future version will "
|
||||
"be switched from False to True for security reasons. Plugin authors should ensure they explicitly "
|
||||
"declare the CSRF protection status in their BlueprintPlugin mixin implementation. "
|
||||
"Recommendation is to enable CSRF protection and exempt views that must not use it with the "
|
||||
"octoprint.plugin.BlueprintPlugin.csrf_exempt decorator."
|
||||
)
|
||||
return False
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_blueprint_api_prefixes(self):
|
||||
"""
|
||||
|
||||
@@ -291,6 +291,9 @@ class AnnouncementPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
|
||||
@@ -161,6 +161,7 @@ class AppKeysPlugin(
|
||||
return NO_CONTENT
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
|
||||
@octoprint.plugin.BlueprintPlugin.csrf_exempt()
|
||||
@no_firstrun_access
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
@@ -196,7 +197,7 @@ class AppKeysPlugin(
|
||||
)
|
||||
return response
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
|
||||
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_decision_poll(self, app_token):
|
||||
result = self._get_pending_by_app_token(app_token)
|
||||
@@ -214,7 +215,7 @@ class AppKeysPlugin(
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>")
|
||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def handle_auth_dialog(self, app_token):
|
||||
user_id = current_user.get_name()
|
||||
@@ -284,6 +285,9 @@ class AppKeysPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False # No API key required to request API access
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True # protect anything that isn't explicitly marked as exempt
|
||||
|
||||
##~~ SimpleApiPlugin mixin
|
||||
|
||||
def get_api_commands(self):
|
||||
|
||||
@@ -356,6 +356,9 @@ class BackupPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ WizardPlugin
|
||||
|
||||
def is_wizard_required(self):
|
||||
|
||||
@@ -40,7 +40,6 @@ $(function () {
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function (e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
|
||||
@@ -74,6 +74,11 @@ class CoreWizardPlugin(
|
||||
else:
|
||||
return {}
|
||||
|
||||
# ~~ BlueprintPlugin API
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
# ~~ WizardPlugin API
|
||||
|
||||
def is_wizard_required(self):
|
||||
|
||||
@@ -134,6 +134,9 @@ class DiscoveryPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
|
||||
@@ -127,6 +127,9 @@ class LoggingPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
def _get_usage(self):
|
||||
import psutil
|
||||
|
||||
|
||||
@@ -609,6 +609,9 @@ class PluginManagerPlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
##~~ EventHandlerPlugin
|
||||
|
||||
def on_event(self, event, payload):
|
||||
|
||||
@@ -1453,6 +1453,9 @@ class SoftwareUpdatePlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
# ~~ Asset API
|
||||
|
||||
def get_assets(self):
|
||||
|
||||
@@ -127,6 +127,7 @@ from octoprint.printer.standard import Printer
|
||||
from octoprint.server.util import (
|
||||
corsRequestHandler,
|
||||
corsResponseHandler,
|
||||
csrfRequestHandler,
|
||||
loginFromApiKeyRequestHandler,
|
||||
requireLoginRequestHandler,
|
||||
)
|
||||
@@ -1916,6 +1917,16 @@ class Server:
|
||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
if plugin.is_blueprint_csrf_protected():
|
||||
self._logger.debug(
|
||||
f"CSRF Protection for Blueprint of plugin {name} is enabled"
|
||||
)
|
||||
blueprint.before_request(csrfRequestHandler)
|
||||
else:
|
||||
self._logger.warning(
|
||||
f"CSRF Protection for Blueprint of plugin {name} is DISABLED"
|
||||
)
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
blueprint.before_request(requireLoginRequestHandler)
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util import (
|
||||
corsRequestHandler,
|
||||
corsResponseHandler,
|
||||
csrfRequestHandler,
|
||||
loginFromApiKeyRequestHandler,
|
||||
loginFromAuthorizationHeaderRequestHandler,
|
||||
noCachingExceptGetResponseHandler,
|
||||
@@ -68,6 +69,7 @@ api.after_request(noCachingExceptGetResponseHandler)
|
||||
api.before_request(corsRequestHandler)
|
||||
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
||||
api.before_request(loginFromApiKeyRequestHandler)
|
||||
api.before_request(csrfRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
# ~~ data from plugins
|
||||
|
||||
@@ -148,6 +148,26 @@ def corsResponseHandler(resp):
|
||||
return resp
|
||||
|
||||
|
||||
def csrfRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for blueprints which checks for CRFS double token on
|
||||
relevant requests & methods.
|
||||
"""
|
||||
from octoprint.server.util.csrf import validate_csrf_request
|
||||
|
||||
if settings().getBoolean(["devel", "enableCsrfProtection"]):
|
||||
validate_csrf_request(_flask.request)
|
||||
|
||||
|
||||
def csrfResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for updating the CSRF cookie on each response.
|
||||
"""
|
||||
from octoprint.server.util.csrf import add_csrf_cookie
|
||||
|
||||
return add_csrf_cookie(resp)
|
||||
|
||||
|
||||
def noCachingResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for blueprints which shall set no caching headers
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""CSRF double cookie implementation"""
|
||||
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import flask
|
||||
|
||||
from octoprint.server.util.flask import OctoPrintFlaskResponse
|
||||
|
||||
exempt_views = set()
|
||||
|
||||
|
||||
def _get_view_location(view):
|
||||
if isinstance(view, str):
|
||||
return view
|
||||
else:
|
||||
return f"{view.__module__}.{view.__name__}"
|
||||
|
||||
|
||||
def add_exempt_view(view):
|
||||
exempt_views.add(_get_view_location(view))
|
||||
|
||||
|
||||
def is_exempt(view):
|
||||
if not view:
|
||||
return False
|
||||
|
||||
return _get_view_location(view) in exempt_views
|
||||
|
||||
|
||||
def generate_csrf_token():
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
|
||||
value = hashlib.sha1(os.urandom(64)).hexdigest()
|
||||
|
||||
secret = flask.current_app.config["SECRET_KEY"]
|
||||
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||
|
||||
return s.dumps(value)
|
||||
|
||||
|
||||
def validate_csrf_tokens(cookie, header):
|
||||
import hmac
|
||||
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
|
||||
if cookie is None or header is None:
|
||||
return False
|
||||
|
||||
secret = flask.current_app.config["SECRET_KEY"]
|
||||
s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token")
|
||||
|
||||
try:
|
||||
# TODO: set max age for values, once we have a REST based heartbeat
|
||||
# that takes care of regular cookie refresh
|
||||
value_cookie = s.loads(cookie)
|
||||
value_header = s.loads(header)
|
||||
return hmac.compare_digest(value_cookie, value_header)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def add_csrf_cookie(response):
|
||||
if not isinstance(response, OctoPrintFlaskResponse):
|
||||
return
|
||||
|
||||
token = generate_csrf_token()
|
||||
response.set_cookie("csrf_token", token, httponly=False)
|
||||
return response
|
||||
|
||||
|
||||
def validate_csrf_request(request):
|
||||
if request.method in ["GET", "HEAD", "OPTIONS"]:
|
||||
# Irrelevant method for CSRF, bypass
|
||||
return
|
||||
|
||||
if getattr(flask.g, "login_via_apikey", False):
|
||||
# API key authorization, bypass
|
||||
return
|
||||
|
||||
if is_exempt(request.endpoint):
|
||||
# marked as exempt, bypass
|
||||
return
|
||||
|
||||
cookie = request.cookies.get("csrf_token", None)
|
||||
header = request.headers.get("X-CSRF-Token", None)
|
||||
|
||||
if not validate_csrf_tokens(cookie, header):
|
||||
flask.abort(400, "CSRF validation failed")
|
||||
|
||||
|
||||
def csrf_exempt(view):
|
||||
add_exempt_view(view)
|
||||
return view
|
||||
@@ -43,6 +43,7 @@ from octoprint.server.util import (
|
||||
require_login_with,
|
||||
validate_local_redirect,
|
||||
)
|
||||
from octoprint.server.util.csrf import add_csrf_cookie
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import sv, to_bytes, to_unicode
|
||||
from octoprint.util.version import get_python_version_string
|
||||
@@ -223,7 +224,9 @@ def login():
|
||||
except Exception:
|
||||
_logger.exception("Error processing theming CSS, ignoring")
|
||||
|
||||
return render_template("login.jinja2", **render_kwargs)
|
||||
resp = make_response(render_template("login.jinja2", **render_kwargs))
|
||||
add_csrf_cookie(resp)
|
||||
return resp
|
||||
|
||||
|
||||
@app.route("/recovery")
|
||||
@@ -254,7 +257,9 @@ def recovery():
|
||||
except Exception:
|
||||
_logger.exception("Error adding backup upload size info, ignoring")
|
||||
|
||||
return render_template("recovery.jinja2", **render_kwargs)
|
||||
resp = make_response(render_template("recovery.jinja2", **render_kwargs))
|
||||
add_csrf_cookie(resp)
|
||||
return resp
|
||||
|
||||
|
||||
@app.route("/cached.gif")
|
||||
@@ -694,6 +699,8 @@ def index():
|
||||
|
||||
if response is None:
|
||||
return abort(404)
|
||||
|
||||
add_csrf_cookie(response)
|
||||
return response
|
||||
|
||||
|
||||
|
||||
@@ -228,7 +228,7 @@ default_settings = {
|
||||
"preemptiveCache": {"exceptions": [], "until": 7},
|
||||
"ipCheck": {"enabled": True, "trustedSubnets": []},
|
||||
"allowFraming": False,
|
||||
"cookies": {"secure": False, "samesite": None},
|
||||
"cookies": {"secure": False, "samesite": "strict"},
|
||||
},
|
||||
"webcam": {
|
||||
"webcamEnabled": True,
|
||||
@@ -471,6 +471,7 @@ default_settings = {
|
||||
"sockJsConnectTimeout": 30,
|
||||
"pluginTimings": False,
|
||||
"enableRateLimiter": True,
|
||||
"enableCsrfProtection": True,
|
||||
},
|
||||
}
|
||||
"""The default settings of the core application."""
|
||||
@@ -891,6 +892,7 @@ class Settings:
|
||||
"logs",
|
||||
]
|
||||
)
|
||||
self.warn_about_risky_settings()
|
||||
|
||||
def _init_basedir(self, basedir):
|
||||
if basedir is not None:
|
||||
@@ -923,6 +925,16 @@ class Settings:
|
||||
if len(folder_map.values()) != len(set(folder_map.values())):
|
||||
raise DuplicateFolderPaths(folders)
|
||||
|
||||
def warn_about_risky_settings(self):
|
||||
if not self.getBoolean(["devel", "enableRateLimiter"]):
|
||||
self._logger.warning(
|
||||
"Rate limiting is disabled, this is a security risk. Do not run this in production."
|
||||
)
|
||||
if not self.getBoolean(["devel", "enableCsrfProtection"]):
|
||||
self._logger.warning(
|
||||
"CSRF Protection is disabled, this is a security risk. Do not run this in production."
|
||||
)
|
||||
|
||||
def _get_default_folder(self, type):
|
||||
folder = default_settings["folder"][type]
|
||||
if folder is None:
|
||||
|
||||
@@ -107,14 +107,75 @@
|
||||
return url;
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getRequestHeaders = function (additional) {
|
||||
OctoPrintClient.prototype.getCookieSuffix = function () {
|
||||
if (!this.options.baseurl) return "";
|
||||
|
||||
try {
|
||||
var url = new URL(this.options.baseurl);
|
||||
} catch (e) {
|
||||
var parsed = new URL(window.location);
|
||||
var path = this.options.baseurl;
|
||||
if (!path || path[0] !== "/") {
|
||||
path = "/" + (path ? path : "");
|
||||
}
|
||||
var url = new URL(parsed.protocol + "//" + parsed.host + path);
|
||||
}
|
||||
|
||||
var port = url.port || (url.protocol === "https:" ? 443 : 80);
|
||||
if (url.pathname && url.pathname !== "/") {
|
||||
var path = url.pathname;
|
||||
if (path.endsWith("/")) {
|
||||
path = path.substring(0, path.length - 1);
|
||||
}
|
||||
return "_P" + port + "_R" + path.replace(/\//, "|");
|
||||
} else {
|
||||
return "_P" + port;
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getCookieName = function (name) {
|
||||
return name + this.getCookieSuffix();
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getCookie = function (name) {
|
||||
name = this.getCookieName(name);
|
||||
return ("; " + document.cookie)
|
||||
.split("; " + name + "=")
|
||||
.pop()
|
||||
.split(";")[0];
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getRequestHeaders = function (method, additional, opts) {
|
||||
if (arguments.length <= 1) {
|
||||
// versions prior 1.8.3 don't know method and opts
|
||||
if (!_.isString(method)) {
|
||||
additional = method;
|
||||
console.warn(
|
||||
"Calling OctoPrintClient.getRequestHeaders with additional " +
|
||||
"headers as the first parameter is deprecated. Please " +
|
||||
"consult the docs about the current signature and adjust " +
|
||||
"your code accordingly."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
method = method || "GET";
|
||||
additional = additional || {};
|
||||
opts = opts || {};
|
||||
|
||||
var headers = $.extend({}, additional);
|
||||
|
||||
if (this.options.apikey) {
|
||||
headers["X-Api-Key"] = this.options.apikey;
|
||||
} else {
|
||||
// no API key, so browser context, so let's make sure the CSRF token
|
||||
// header is set
|
||||
var csrfToken = this.getCookie("csrf_token");
|
||||
if (!/^(GET|HEAD|OPTIONS)$/.test(method) && csrfToken && !opts.crossDomain) {
|
||||
headers["X-CSRF-Token"] = csrfToken;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.locale !== undefined) {
|
||||
headers["X-Locale"] = this.options.locale;
|
||||
}
|
||||
@@ -134,7 +195,7 @@
|
||||
opts.url = urlToCall;
|
||||
}
|
||||
|
||||
var headers = this.getRequestHeaders(opts.headers);
|
||||
var headers = this.getRequestHeaders(method, opts.headers, opts);
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
params.type = method;
|
||||
@@ -292,14 +353,15 @@
|
||||
deferred.notify({loaded: e.loaded, total: e.total});
|
||||
});
|
||||
|
||||
var headers = this.getRequestHeaders();
|
||||
var method = "POST";
|
||||
var headers = this.getRequestHeaders(method);
|
||||
|
||||
var urlToCall = url;
|
||||
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
|
||||
urlToCall = this.getBaseUrl() + url;
|
||||
}
|
||||
|
||||
request.open("POST", urlToCall);
|
||||
request.open(method, urlToCall);
|
||||
_.each(headers, function (value, key) {
|
||||
request.setRequestHeader(key, value);
|
||||
});
|
||||
|
||||
@@ -202,6 +202,21 @@ $(function () {
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
$.ajaxSetup({
|
||||
beforeSend: function (xhr, settings) {
|
||||
// we already do that in the js client lib, but a lot of plugins don't use
|
||||
// that but rather use $.ajax directly, so we need to do it here as well
|
||||
var csrfToken = OctoPrint.getCookie("csrf_token");
|
||||
if (
|
||||
!/^(GET|HEAD|OPTIONS)$/.test(settings.type) &&
|
||||
csrfToken &&
|
||||
!this.crossDomain
|
||||
) {
|
||||
xhr.setRequestHeader("X-CSRF-Token", csrfToken);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
|
||||
@@ -219,7 +234,8 @@ $(function () {
|
||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||
options: {
|
||||
dropZone: null,
|
||||
pasteZone: null
|
||||
pasteZone: null,
|
||||
headers: OctoPrint.getRequestHeaders("POST")
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -770,7 +770,6 @@ $(function () {
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function (e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
|
||||
Reference in new issue
Block a user