From e4d083028c5064599a2df9bf67254bf9874eb30c Mon Sep 17 00:00:00 2001 From: Matthias Urlichs Date: Sun, 27 Jan 2019 19:00:31 +0100 Subject: [PATCH] hashlib fix from razer --- .../plugins/pluginmanager/__init__.py | 20 ++-- .../plugins/softwareupdate/__init__.py | 33 +++--- src/octoprint/server/api/files.py | 13 ++- src/octoprint/server/api/printer_profiles.py | 9 +- src/octoprint/server/api/settings.py | 15 +-- src/octoprint/server/api/slicing.py | 13 ++- src/octoprint/server/api/timelapse.py | 9 +- src/octoprint/server/util/__init__.py | 4 +- src/octoprint/server/util/flask.py | 101 +++++++----------- src/octoprint/server/util/sockjs.py | 2 +- src/octoprint/server/views.py | 18 ++-- src/octoprint/settings.py | 8 +- 12 files changed, 125 insertions(+), 120 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 500d78d5c..f425fceea 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -306,14 +306,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def etag(): import hashlib hash = hashlib.sha1() - hash.update(repr(self._get_plugins())) - hash.update(str(self._repository_available)) - hash.update(repr(self._repository_plugins)) - hash.update(str(self._notices_available)) - hash.update(repr(self._notices)) - hash.update(repr(safe_mode)) - hash.update(repr(self._connectivity_checker.online)) - hash.update(repr(_DATA_FORMAT_VERSION)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + + hash_update(repr(self._get_plugins())) + hash_update(str(self._repository_available)) + hash_update(repr(self._repository_plugins)) + hash_update(str(self._notices_available)) + hash_update(repr(self._notices)) + hash_update(repr(safe_mode)) + hash_update(repr(self._connectivity_checker.online)) + hash_update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() def condition(): diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 8505ed84e..990455ce9 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -549,28 +549,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, if targets is None: targets = checks.keys() - import hashlib hash = hashlib.sha1() + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) targets = sorted(targets) for target in targets: current_hash = self._get_check_hash(checks.get(target, dict())) if target in self._version_cache and not force: data = self._version_cache[target] - hash.update(current_hash) - hash.update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"])) - hash.update(repr(data["information"])) - hash.update(str(data["available"])) - hash.update(str(data["possible"])) - hash.update(str(data.get("online", None))) + hash_update(current_hash) + hash_update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"])) + hash_update(repr(data["information"])) + hash_update(str(data["available"])) + hash_update(str(data["possible"])) + hash_update(str(data.get("online", None))) - hash.update(",".join(targets)) + hash_update(",".join(targets)) - hash.update(str(self._environment_supported)) - hash.update(str(self._version_cache_timestamp)) - hash.update(str(self._connectivity_checker.online)) - hash.update(str(self._update_in_progress)) - hash.update(self.DATA_FORMAT_VERSION) + hash_update(str(self._environment_supported)) + hash_update(str(self._version_cache_timestamp)) + hash_update(str(self._connectivity_checker.online)) + hash_update(str(self._update_in_progress)) + hash_update(self.DATA_FORMAT_VERSION) return hash.hexdigest() def condition(): @@ -772,7 +774,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return "{" + ", ".join(lines) + "}" hash = hashlib.md5() - hash.update(dict_to_sorted_repr(check)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(dict_to_sorted_repr(check)) return hash.hexdigest() def _get_current_version(self, target, check, force=False, online=None): diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 73afe8dc2..569b25f5b 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -76,15 +76,18 @@ def _create_etag(path, filter, recursive, lm=None): return None hash = hashlib.sha1() - hash.update(str(lm)) - hash.update(str(filter)) - hash.update(str(recursive)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(str(lm)) + hash_update(str(filter)) + hash_update(str(recursive)) if path.endswith("/files") or path.endswith("/files/sdcard"): # include sd data in etag - hash.update(repr(sorted(printer.get_sd_files(), key=lambda x: x[0]))) + hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: x[0]))) - hash.update(_DATA_FORMAT_VERSION) # increment version if we change the API format + hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format return hash.hexdigest() diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index 172017e42..b848f497b 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -30,9 +30,12 @@ def _etag(lm=None): import hashlib hash = hashlib.sha1() - hash.update(str(lm)) - hash.update(repr(printerProfileManager.get_default())) - hash.update(repr(printerProfileManager.get_current())) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(str(lm)) + hash_update(repr(printerProfileManager.get_default())) + hash_update(repr(printerProfileManager.get_current())) return hash.hexdigest() diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 34385c0df..8e9797c24 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -47,25 +47,28 @@ def _etag(lm=None): import hashlib hash = hashlib.sha1() + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) # last modified timestamp - hash.update(str(lm)) + hash_update(str(lm)) # effective config from config.yaml + overlays - hash.update(repr(settings().effective)) + hash_update(repr(settings().effective)) # might duplicate settings().effective, but plugins might also inject additional keys into the settings # output that are not stored in config.yaml - hash.update(repr(sorted_plugin_settings)) + hash_update(repr(sorted_plugin_settings)) # connection options are also part of the settings - hash.update(repr(connection_options)) + hash_update(repr(connection_options)) # if the list of plugins changes, the settings structure changes too - hash.update(repr(plugins)) + hash_update(repr(plugins)) # and likewise if the role of the user changes - hash.update(repr(roles)) + hash_update(repr(roles)) return hash.hexdigest() diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 43597d906..1c7f8a42c 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -40,7 +40,10 @@ def _etag(configured, lm=None): import hashlib hash = hashlib.sha1() - hash.update(str(lm)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(str(lm)) if configured: slicers = slicingManager.configured_slicers @@ -51,11 +54,11 @@ def _etag(configured, lm=None): for slicer in sorted(slicers): slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) - hash.update(slicer) - hash.update(str(slicer_impl.is_slicer_configured())) - hash.update(str(slicer == default_slicer)) + hash_update(slicer) + hash_update(str(slicer_impl.is_slicer_configured())) + hash_update(str(slicer == default_slicer)) - hash.update(_DATA_FORMAT_VERSION) # increment version if we change the API format + hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format return hash.hexdigest() diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 8642512d4..2cbc18812 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -66,9 +66,12 @@ def _etag(unrendered, lm=None): import hashlib hash = hashlib.sha1() - hash.update(str(lm)) - hash.update(repr(config)) - hash.update(repr(_DATA_FORMAT_VERSION)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(str(lm)) + hash_update(repr(config)) + hash_update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 45b855ad5..51c15d345 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -6,6 +6,8 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import base64 +import sys +PY3 = sys.version_info[0] == 3 from octoprint.settings import settings import octoprint.timelapse @@ -282,5 +284,5 @@ def get_plugin_hash(): import hashlib plugin_hash = hashlib.sha1() - plugin_hash.update(",".join(ui_plugins)) + plugin_hash.update(",".join(ui_plugins).encode('utf-8')) return plugin_hash.hexdigest() diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 1f69cea7c..48e20588a 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# coding=utf-8 from __future__ import absolute_import, division, print_function from flask import make_response @@ -13,7 +13,6 @@ import flask.json import flask_login import flask_principal import flask_assets -import io import webassets.updater import webassets.utils import functools @@ -155,7 +154,7 @@ def fix_webassets_cache(): import shutil if not os.path.exists(self.directory): - error_logger.warning("Cache directory {} doesn't exist, not going " + error_logger.warn("Cache directory {} doesn't exist, not going " "to attempt to write cache file".format(self.directory)) md5 = '%s' % cache.make_md5(self.V, key) @@ -178,7 +177,7 @@ def fix_webassets_cache(): from webassets.cache import make_md5 if not os.path.exists(self.directory): - error_logger.warning("Cache directory {} doesn't exist, not going " + error_logger.warn("Cache directory {} doesn't exist, not going " "to attempt to read cache file".format(self.directory)) return None @@ -191,7 +190,7 @@ def fix_webassets_cache(): filename = os.path.join(self.directory, '%s' % hash) try: - f = io.open(filename, 'rb') + f = open(filename, 'rb') except IOError as e: if e.errno != errno.ENOENT: error_logger.exception("Got an exception while trying to open webasset file {}".format(filename)) @@ -538,78 +537,54 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface): #~~ passive login helper -_cached_local_networks = None -def _local_networks(): - global _cached_local_networks - - if _cached_local_networks is None: - logger = logging.getLogger(__name__) - local_networks = netaddr.IPSet([]) - for entry in settings().get(["accessControl", "localNetworks"]): - network = netaddr.IPNetwork(entry) - local_networks.add(network) - logger.debug("Added network {} to localNetworks".format(network)) - - if network.version == 4: - network_v6 = network.ipv6() - local_networks.add(network_v6) - logger.debug("Also added v6 representation of v4 network {} = {} to localNetworks".format(network, network_v6)) - - _cached_local_networks = local_networks - - return _cached_local_networks - def passive_login(): - logger = logging.getLogger(__name__) + user = flask_login.current_user - if octoprint.server.userManager.enabled: - user = octoprint.server.userManager.login_user(flask_login.current_user) - else: - user = flask_login.current_user - - remote_address = get_remote_address(flask.request) - ip_check_enabled = settings().getBoolean(["server", "ipCheck", "enabled"]) - ip_check_trusted = settings().get(["server", "ipCheck", "trustedSubnets"]) + remoteAddr = get_remote_address(flask.request) + ipCheckEnabled = settings().getBoolean(["server", "ipCheck", "enabled"]) + ipCheckTrusted = settings().get(["server", "ipCheck", "trustedSubnets"]) if isinstance(user, LocalProxy): # noinspection PyProtectedMember user = user._get_current_object() - logger.info("Passively logging in user {} from {}".format(user.get_id(), remote_address)) + def login(u): + # login known user + if not u.is_anonymous: + u = octoprint.server.userManager.login_user(u) + flask_login.login_user(u) + flask_principal.identity_changed.send(flask.current_app._get_current_object(), + identity=flask_principal.Identity(u.get_id())) + if hasattr(u, "session"): + flask.session["usersession.id"] = u.session + flask.g.user = u + return u - response = user.asDict() - response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, - additional_private=ip_check_trusted) - return flask.jsonify(response) + if user is not None and user.is_active: + # login known user + logging.getLogger(__name__).info("Passively logging in user {} from {}".format(user.get_id(), remoteAddr)) + user = login(user) elif settings().getBoolean(["accessControl", "autologinLocal"]) \ and settings().get(["accessControl", "autologinAs"]) is not None \ and settings().get(["accessControl", "localNetworks"]) is not None: - autologin_as = settings().get(["accessControl", "autologinAs"]) - local_networks = _local_networks() - logger.debug("Checking if remote address {} is in localNetworks ({!r})".format(remote_address, local_networks)) + autologinAs = settings().get(["accessControl", "autologinAs"]) + localNetworks = netaddr.IPSet([]) + for ip in settings().get(["accessControl", "localNetworks"]): + localNetworks.add(ip) try: - if netaddr.IPAddress(remote_address) in local_networks: - user = octoprint.server.userManager.findUser(autologin_as) - if user is not None and user.is_active(): - user = octoprint.server.userManager.login_user(user) - flask.session["usersession.id"] = user.session - flask.g.user = user - flask_login.login_user(user) - flask_principal.identity_changed.send(flask.current_app._get_current_object(), - identity=flask_principal.Identity(user.get_id())) + if netaddr.IPAddress(remoteAddr) in localNetworks: + autologin_user = octoprint.server.userManager.find_user(autologinAs) + if autologin_user is not None and user.is_active: + autologin_user = octoprint.server.userManager.login_user(autologin_user) - logger.info("Passively logging in user {} from {} via autologin".format(user.get_id(), - remote_address)) - - response = user.asDict() - response["_is_external_client"] = ip_check_enabled and not is_lan_address(remote_address, - additional_private=ip_check_trusted) - return flask.jsonify(response) + logging.getLogger(__name__).info("Passively logging in user {} from {} via autologin".format(user.get_id(), remoteAddr)) + user = login(autologin_user) except: - logger.exception("Could not autologin user {} for networks {}".format(autologin_as, localNetworks)) + logger = logging.getLogger(__name__) + logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) response = user.as_dict() response["_is_external_client"] = ipCheckEnabled and not is_lan_address(remoteAddr, @@ -869,7 +844,7 @@ class PreemptiveCache(object): cache_data = None with self._lock: try: - with io.open(self.cachefile, 'rt', encoding='utf-8') as f: + with open(self.cachefile, "r") as f: cache_data = yaml.safe_load(f) except IOError as e: import errno @@ -893,7 +868,7 @@ class PreemptiveCache(object): with self._lock: try: - with atomic_write(self.cachefile, mode='wb', max_permissions=0o666) as handle: + with atomic_write(self.cachefile, "wb", max_permissions=0o666) as handle: yaml.safe_dump(data, handle,default_flow_style=False, indent=4, allow_unicode=True) except: self._logger.exception("Error while writing {}".format(self.cachefile)) @@ -1494,7 +1469,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): def asset_exists(category, asset): exists = os.path.exists(os.path.join(basefolder, asset)) if not exists: - logger.warning("Plugin {} is referring to non existing {} asset {}".format(name, category, asset)) + logger.warn("Plugin {} is referring to non existing {} asset {}".format(name, category, asset)) return exists if "js" in all_assets: diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 4d1d13c9a..2dafe3820 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -139,7 +139,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, import hashlib plugin_hash = hashlib.md5() - plugin_hash.update(",".join(ui_plugins)) + plugin_hash.update(",".join(ui_plugins).encode('utf-8')) config_hash = settings().config_hash diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index b282d9611..f23027dab 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -293,13 +293,15 @@ def index(): import hashlib hash = hashlib.sha1() - hash.update(octoprint.__version__) - hash.update(octoprint.server.UI_API_KEY) - hash.update(",".join(sorted(files))) + def hash_update(value): + hash.update(value.encode('utf-8')) + hash_update(octoprint.__version__) + hash_update(octoprint.server.UI_API_KEY) + hash_update(",".join(sorted(files))) if lastmodified: - hash.update(lastmodified) + hash_update(lastmodified) for add in additional: - hash.update(str(add)) + hash_update(str(add)) return hash.hexdigest() decorated_view = view @@ -902,9 +904,11 @@ def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None): import hashlib hash = hashlib.sha1() - hash.update(",".join(sorted(files))) + def hash_update(value): + hash.update(value.encode('utf-8')) + hash_update(",".join(sorted(files))) if lastmodified: - hash.update(lastmodified) + hash_update(lastmodified) return hash.hexdigest() diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d7632483c..e73ec656b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -803,11 +803,11 @@ class Settings(object): # if it's a template matcher, we need to add a key to associate with the matcher output import hashlib key_hash = hashlib.md5() - key_hash.update(result["regex"]) + key_hash.update(result["regex"].encode('utf-8')) result["key"] = key_hash.hexdigest() template_key_hash = hashlib.md5() - template_key_hash.update(result["template"]) + template_key_hash.update(result["template"].encode('utf-8')) result["template_key"] = template_key_hash.hexdigest() elif "children" in result: @@ -831,7 +831,7 @@ class Settings(object): def effective_hash(self): import hashlib hash = hashlib.md5() - hash.update(self.effective_yaml) + hash.update(self.effective_yaml.encode('utf-8')) return hash.hexdigest() @property @@ -843,7 +843,7 @@ class Settings(object): def config_hash(self): import hashlib hash = hashlib.md5() - hash.update(self.config_yaml) + hash.update(self.config_yaml.encode('utf-8')) return hash.hexdigest() @property