From 3c8f8c84f4b9a13494d831dd8a736c21feaee12b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 12 Sep 2022 17:21:51 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A5=85=20Improve=20password=20hash=20migr?= =?UTF-8?q?ation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - users.yaml is now versioned, and a backup is made on version change. Thus, before any of the new hashes are being saved to it, a backup with the old ones will be made, here users.v1.yaml. - The no longer needed salt is removed from the config if no legacy hashes are left in users.yaml. Prior to this removal however, a backup of config.yaml is made, config.cleanup_legacy_hashes.yaml. When rolling back to an earlier version of OctoPrint, moving both backups back over to config.yaml and users.yaml respectively and restarting will restore the ability to login again. --- docs/configuration/config_yaml.rst | 6 +-- docs/features/accesscontrol.rst | 19 ++++++-- src/octoprint/access/users.py | 64 ++++++++++++++++++-------- src/octoprint/settings.py | 1 - tests/access/users/test_usermanager.py | 3 +- 5 files changed, 64 insertions(+), 29 deletions(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index e1c126dcb..baa7e5519 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -72,10 +72,6 @@ Use the following settings to enable access control: # If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint. addRemoteUsers: false - # Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your - # existing accounts. - salt: someSecretSalt - .. _sec-configuration-config_yaml-api: API @@ -451,7 +447,7 @@ Use the following settings to enable or disable OctoPrint features: # whether G90/G91 also influence absolute/relative mode of extruders g90InfluencesExtruder: false - + # Replace all special characters and spaces with text equivalent to make them universally compatible. # Most OS filesystems work fine with unicode characters, but just in case you can revert to the # older behaviour by setting this to true. diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 218e3bb9c..f9118f8b3 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -165,7 +165,7 @@ further down there's also a dedicated list of steps for OctoPi specifically. 1. Shutdown OctoPrint 2. Make a backup of your config.yaml -3. Open it in a text editor (e.g. nano). Right at the very top it'll say something like +3. Open it in a text editor (e.g. nano). Look if right at the very top it says something like this: .. code-block:: yaml @@ -173,7 +173,7 @@ further down there's also a dedicated list of steps for OctoPi specifically. accessControl: salt: aabbccddee1234523452345 - Edit this, adding lines so it looks like this (making absolutely sure not to touch the + If so, edit this, adding lines so it looks like this (making absolutely sure not to touch the salt line): .. code-block:: yaml @@ -187,6 +187,19 @@ further down there's also a dedicated list of steps for OctoPi specifically. - "::1/128" - "" + Otherwise, add the following lines to the very top of the file, making sure to keep the + indentation: + + .. code-block:: yaml + + accessControl: + autologinLocal: true + autologinAs: "" + localNetworks: + - "127.0.0.0/8" + - "::1/128" + - "" + 4. Restart OctoPrint, check that everything works. This will automatically log you in as the user you specified whenver you connect to @@ -200,7 +213,7 @@ the following commands: 1. ``sudo service octoprint stop`` 2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back`` -3. ``nano ~/.octoprint/config.yaml, make the edits as described above`` +3. ``nano ~/.octoprint/config.yaml``, make the edits as described above 4. ``sudo service octoprint start`` If something went wrong, you can restore the config backup with diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 1c5d2b84e..6533d68e8 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -4,6 +4,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import hashlib import logging import os +import shutil import time import uuid @@ -143,20 +144,7 @@ class UserManager(GroupChangeListener): return passwordhash.hash(password) @staticmethod - def create_legacy_password_hash(password, salt=None, settings=None): - if not salt: - if settings is None: - settings = s() - salt = settings.get(["accessControl", "salt"]) - if salt is None: - import string - from random import choice - - chars = string.ascii_lowercase + string.ascii_uppercase + string.digits - salt = "".join(choice(chars) for _ in range(32)) - settings.set(["accessControl", "salt"], salt) - settings.save() - + def create_legacy_password_hash(password, salt): return hashlib.sha512( to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt) ).hexdigest() @@ -167,13 +155,17 @@ class UserManager(GroupChangeListener): return False if user.check_password(password): - # password matches hash, correct password + # password matches, correct password return True else: # new hash doesn't match, check legacy hash - legacy_hash = UserManager.create_legacy_password_hash( - password, settings=self._settings + salt = self._settings.get(["accessControl"], asdict=True, merged=True).get( + "salt", None ) + if salt is None: + return False + + legacy_hash = UserManager.create_legacy_password_hash(password, salt) if user.check_password(legacy_hash, legacy=True): # legacy hash matches, we migrate the stored password hash to the new one and return True since it's the correct password self.change_user_password(username, password) @@ -182,6 +174,9 @@ class UserManager(GroupChangeListener): # legacy hash doesn't match either, wrong password return False + def cleanup_legacy_hashes(self): + pass + def signature_key_for_user(self, username, salt=None): return self.create_password_hash(username, salt=salt) @@ -490,6 +485,8 @@ class LoginStatusListener: class FilebasedUserManager(UserManager): + FILE_VERSION = 2 + def __init__(self, group_manager, path=None, settings=None): UserManager.__init__(self, group_manager, settings=settings) @@ -521,6 +518,17 @@ class FilebasedUserManager(UserManager): ) raise CorruptUserStorage() + version = data.pop("_version", 1) + if version != self.FILE_VERSION: + self._logger.info( + f"Making a backup of the users.yaml file before migrating from version {version} to {self.FILE_VERSION}" + ) + shutil.copy( + self._userfile, + os.path.splitext(self._userfile)[0] + f".v{version}.yaml", + ) + self._dirty = True + for name, attributes in data.items(): if not isinstance(attributes, dict): continue @@ -568,6 +576,8 @@ class FilebasedUserManager(UserManager): if self._dirty: self._save() + self.cleanup_legacy_hashes() + self._customized = True else: self._customized = False @@ -576,7 +586,7 @@ class FilebasedUserManager(UserManager): if not self._dirty and not force: return - data = {} + data = {"_version": self.FILE_VERSION} for name, user in self._users.items(): if not user or not isinstance(user, User): continue @@ -781,6 +791,24 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(user) + def cleanup_legacy_hashes(self): + no_legacy = all( + map( + lambda u: u._passwordHash.startswith("$argon2id$") + or u._passwordHash.startswith("$pbkdf2-"), + self._users.values(), + ) + ) + salt = self._settings.get(["accessControl"], asdict=True, merged=True).get( + "salt", None + ) + + if no_legacy and salt: + # no legacy hashs left, kill salt + self._settings.backup("cleanup_legacy_hashes") + self._settings.remove(["accessControl", "salt"]) + self._settings.save() + def signature_key_for_user(self, username, salt=None): if username not in self._users: raise UnknownUser(username) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 032b23c03..d598419a7 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -402,7 +402,6 @@ default_settings = { "controls": [], "system": {"actions": []}, "accessControl": { - "salt": None, "userManager": "octoprint.access.users.FilebasedUserManager", "groupManager": "octoprint.access.groups.FilebasedGroupManager", "permissionManager": "octoprint.access.permissions.PermissionManager", diff --git a/tests/access/users/test_usermanager.py b/tests/access/users/test_usermanager.py index f1faa1f7d..b566492dc 100644 --- a/tests/access/users/test_usermanager.py +++ b/tests/access/users/test_usermanager.py @@ -18,7 +18,6 @@ class UserManagerTest(unittest.TestCase): """Test for issue #1891""" password = "password with ümläutß" - salt = "abc" # should not throw an exception - octoprint.access.users.UserManager.create_password_hash(password, salt=salt) + octoprint.access.users.UserManager.create_password_hash(password)