From 57a58b3bd7fbe27ac62777e6f54ce4d1564911b6 Mon Sep 17 00:00:00 2001 From: Bernd Zeimetz Date: Mon, 18 Dec 2017 00:38:20 +0100 Subject: [PATCH 1/3] Trust basic authentication headers for user login. This is my suggestion on how to handle basic authentication for users mananaged by OctoPrint's UserManager. In my opinion OctoPrint should not be doing Basic Authentication on its own. The commen case is that it runs on some slow hardware which its not able to handle stupid bots trying out thousands of passwords in short time. Also you want to protect it as much as possible from the outside to ensure that the basd internet can't break your 72h print after 71 hours by brute-forcing passwords. So I'm introducing an accessControl: trustBasicAuthentication config option. If enabled, it will take the user name from the Authorization header, check if the user exists and is enabled - and if so, just login the user. --- AUTHORS.md | 1 + src/octoprint/server/__init__.py | 18 ++++++++++++++++ src/octoprint/server/api/__init__.py | 3 ++- src/octoprint/server/util/__init__.py | 31 +++++++++++++++++++++++++++ src/octoprint/settings.py | 3 ++- 5 files changed, 54 insertions(+), 2 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index a08602296..b8b427a2b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -86,6 +86,7 @@ date of first contribution): * [Peter Backx](https://github.com/pbackx) * [Josh Major](https://github.com/astateofblank) * ["alex-gh"](https://github.com/alex-gh) + * [Bernd Zeimetz](https://github.com/bzed) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index a9488a765..b034f613b 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -147,6 +147,19 @@ def load_user(id): return None +def load_user_from_request(request): + header = request.headers.get('Authorization') + if header: + header = header.replace('Basic ', '', 1) + try: + header = base64.b64decode(header) + except TypeError: + return None + id = header.split(':')[0] + user = userManager.findUser(userid=id) + if user: + return user + return None def unauthorized_user(): from flask import abort @@ -446,6 +459,11 @@ class Server(object): loginManager.session_protection = "strong" loginManager.user_callback = load_user loginManager.unauthorized_callback = unauthorized_user + + # login users authenticated by basic auth + if self._settings.get(["accessControl", "trustBasicAuthentication"]): + loginManager.request_callback = load_user_from_request + if not userManager.enabled: loginManager.anonymous_user = users.DummyUser principals.identity_loaders.appendleft(users.dummy_identity_loader) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 184567afe..c68844a40 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -19,7 +19,7 @@ import octoprint.server import octoprint.plugin from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, corsResponseHandler +from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromRequest, corsRequestHandler, corsResponseHandler from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login @@ -47,6 +47,7 @@ api.after_request(noCachingExceptGetResponseHandler) api.before_request(corsRequestHandler) api.before_request(enforceApiKeyRequestHandler) +api.before_request(loginFromRequest) api.before_request(loginFromApiKeyRequestHandler) api.after_request(corsResponseHandler) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index f18d05a7c..ab5940533 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -5,6 +5,8 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" +import base64 + from octoprint.settings import settings import octoprint.timelapse import octoprint.server @@ -75,6 +77,35 @@ def loginFromApiKeyRequestHandler(): return _flask.make_response("Invalid API key", 403) +def loginFromRequest(): + """ + ``before_request`` handler for creating login sessions based on the Authorization header. + """ + + if not settings().get(["accessControl", "trustBasicAuthentication"]): + return + + header = _flask.request.headers.get('Authorization') + if header: + header = header.replace('Basic ', '', 1) + try: + header = base64.b64decode(header) + except TypeError: + return + id = header.split(':')[0] + if octoprint.server.userManager.enabled: + user = octoprint.server.userManager.findUser(userid=id) + else: + # what should we really do if the user manager is disabled + # and basic auth activated? + return + + if user is not None and _flask.ext.login.login_user(user, remember=False): + _flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(), + identity=_flask.ext.principal.Identity(user.get_id())) + return + + def corsRequestHandler(): """ ``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index f8e5b09dc..f42ff6677 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -301,7 +301,8 @@ default_settings = { "userfile": None, "autologinLocal": False, "localNetworks": ["127.0.0.0/8"], - "autologinAs": None + "autologinAs": None, + "trustBasicAuthentication": False }, "slicing": { "enabled": True, From fcf7358855e851451e66c95588339004243a3e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 5 Feb 2018 15:37:46 +0100 Subject: [PATCH 2/3] BasicAuth: Check PW too by default Also slightly refactored to deduplicate. --- src/octoprint/server/__init__.py | 13 +---- src/octoprint/server/api/__init__.py | 4 +- src/octoprint/server/util/__init__.py | 79 +++++++++++++++++++-------- src/octoprint/settings.py | 3 +- 4 files changed, 60 insertions(+), 39 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index b034f613b..cc8b6bcfb 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -148,18 +148,7 @@ def load_user(id): return None def load_user_from_request(request): - header = request.headers.get('Authorization') - if header: - header = header.replace('Basic ', '', 1) - try: - header = base64.b64decode(header) - except TypeError: - return None - id = header.split(':')[0] - user = userManager.findUser(userid=id) - if user: - return user - return None + return util.get_user_for_authorization_header(request.headers.get('Authorization')) def unauthorized_user(): from flask import abort diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index c68844a40..f0dfaa6e8 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -19,7 +19,7 @@ import octoprint.server import octoprint.plugin from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromRequest, corsRequestHandler, corsResponseHandler +from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login @@ -47,7 +47,7 @@ api.after_request(noCachingExceptGetResponseHandler) api.before_request(corsRequestHandler) api.before_request(enforceApiKeyRequestHandler) -api.before_request(loginFromRequest) +api.before_request(loginFromAuthorizationHeaderRequestHandler) api.before_request(loginFromApiKeyRequestHandler) api.after_request(corsResponseHandler) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index ab5940533..30f13d2fc 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -70,40 +70,36 @@ def loginFromApiKeyRequestHandler(): return user = get_user_for_apikey(apikey) - if user is not None and _flask.ext.login.login_user(user, remember=False): - _flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(), - identity=_flask.ext.principal.Identity(user.get_id())) - else: + if not loginUser(user): return _flask.make_response("Invalid API key", 403) -def loginFromRequest(): +def loginFromAuthorizationHeaderRequestHandler(): """ ``before_request`` handler for creating login sessions based on the Authorization header. """ - if not settings().get(["accessControl", "trustBasicAuthentication"]): - return + authorization_header = get_authorization_header(_flask.request) + user = get_user_for_authorization_header(authorization_header) + loginUser(user) - header = _flask.request.headers.get('Authorization') - if header: - header = header.replace('Basic ', '', 1) - try: - header = base64.b64decode(header) - except TypeError: - return - id = header.split(':')[0] - if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.findUser(userid=id) - else: - # what should we really do if the user manager is disabled - # and basic auth activated? - return - if user is not None and _flask.ext.login.login_user(user, remember=False): - _flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(), +def loginUser(user, remember=False): + """ + Logs the provided ``user`` into Flask Login and Principal if not None and active + + Args: + user: the User to login. May be None in which case the login will fail + remember: Whether to set the ``remember`` flag on the Flask Login operation + + Returns: (bool) True if the login succeeded, False otherwise + + """ + if user is not None and user.is_active() and _flask.ext.login.login_user(user, remember=remember): + _flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(), identity=_flask.ext.principal.Identity(user.get_id())) - return + return True + return False def corsRequestHandler(): @@ -202,6 +198,36 @@ def get_user_for_apikey(apikey): return None +def get_user_for_authorization_header(header): + if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]): + return None + + if header is None: + return None + + if not header.startswith("Basic "): + # we currently only support Basic Authentication + return None + + header = header.replace('Basic ', '', 1) + try: + header = base64.b64decode(header) + except TypeError: + return None + + name, password = header.split(':', 1) + if not octoprint.server.userManager.enabled: + return None + + user = octoprint.server.userManager.findUser(userid=name) + if settings().getBoolean(["accessControl", "checkBasicAuthenticationPassword"]) \ + and not octoprint.server.userManager.checkPassword(name, password): + # password check enabled and password don't match + return None + + return user + + def get_api_key(request): # Check Flask GET/POST arguments if hasattr(request, "values") and "apikey" in request.values: @@ -219,6 +245,11 @@ def get_api_key(request): return None +def get_authorization_header(request): + # Tornado and Flask headers + return request.headers.get("Authorization") + + def get_plugin_hash(): from octoprint.plugin import plugin_manager diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index f42ff6677..e65af226c 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -302,7 +302,8 @@ default_settings = { "autologinLocal": False, "localNetworks": ["127.0.0.0/8"], "autologinAs": None, - "trustBasicAuthentication": False + "trustBasicAuthentication": False, + "checkBasicAuthenticationPassword": True }, "slicing": { "enabled": True, From fca7005bfaf65a662f765177790bc74689b29fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 5 Feb 2018 15:54:12 +0100 Subject: [PATCH 3/3] [Docs] Document basic auth config settings --- docs/configuration/config_yaml.rst | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index f469c2086..c5df5727f 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -36,7 +36,7 @@ Use the following settings to enable access control: # If set to true, will automatically log on clients originating from any of the networks defined in # "localNetworks" as the user defined in "autologinAs". Defaults to false. - autologinLocal: true + autologinLocal: false # The name of the user to automatically log on clients originating from "localNetworks" as. Must # be the name of one of your configured users. @@ -51,6 +51,17 @@ Use the following settings to enable access control: - 127.0.0.0/8 - 192.168.1.0/24 + # Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of + # OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will + # be logged into OctoPrint as the user user during Basic Authentication. Your should ONLY ENABLE THIS if your + # OctoPrint instance is only accessible through a connection locked down through Basic Authentication! + trustBasicAuthentication: false + + # Whether to also check the password provided through Basic Authentication if the Basic Authentication + # header is to be trusted. Disabling this will only match the user name in the Basic Authentication + # header and login the user without further checks. Use with caution. + checkBasicAuthenticationPassword: true + .. _sec-configuration-config_yaml-api: API