Merge branch 'master' into maintenance
This commit is contained in:
commit
24e6fcf170
52 files changed
+2677
-1956
No files matched your search
@@ -1,5 +1,8 @@
|
||||
accessControl:
|
||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||
devel:
|
||||
enableRateLimiter: false
|
||||
enableCsrfProtection: false
|
||||
plugins:
|
||||
virtual_printer:
|
||||
enabled: true
|
||||
|
||||
+3
-3
@@ -24,10 +24,10 @@ maintenance 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
fix/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
improve/.* 1.9.0 fa2c4680cca0d1d6b46e6c1ed68ceea4d9b79afb pep440-dev
|
||||
|
||||
# staging/bugfix is the branch for preparation of the 1.8.1 bugfix release
|
||||
# staging/bugfix is the branch for preparation of the 1.8.3 bugfix release
|
||||
# so are any bug/... branches
|
||||
staging/bugfix 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
|
||||
bug/.* 1.8.2 260a1aef11432c421246019e25b6b744abbaed60 pep440-dev
|
||||
staging/bugfix 1.8.3 87f4a4e8c967dab147beb6213cbf61cca32bec62 pep440-dev
|
||||
bug/.* 1.8.3 87f4a4e8c967dab147beb6213cbf61cca32bec62 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.8.0rc6
|
||||
# so is regressionfix/...
|
||||
|
||||
+1
-6
@@ -22,11 +22,8 @@ thanks to everyone who contributed!
|
||||
* Creality3D
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Douglas Floyd
|
||||
* Dr. Frank Wester
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* James Mackay
|
||||
* Jeff Green
|
||||
@@ -69,8 +66,6 @@ thanks to everyone who contributed!
|
||||
* Steve Dougherty
|
||||
* Steve Thompson
|
||||
* TJ Horner
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
* Yehuda Katz
|
||||
|
||||
and 2209 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
and 2188 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
+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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
- "<yourAddressRange>"
|
||||
|
||||
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: "<yourUsername>"
|
||||
localNetworks:
|
||||
- "127.0.0.0/8"
|
||||
- "::1/128"
|
||||
- "<yourAddressRange>"
|
||||
|
||||
4. Restart OctoPrint, check that everything works.
|
||||
|
||||
This will automatically log you in as the user you specified whenever 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -34,6 +34,7 @@ bundled_plugins = [
|
||||
"OctoPrint-PiSupport>=2022.3.28",
|
||||
]
|
||||
core_deps = [
|
||||
"argon2_cffi>=21.3.0,<22",
|
||||
"cachelib>=0.2,<0.3",
|
||||
"Click>=8.0.3,<9",
|
||||
"colorlog>=6,<7",
|
||||
@@ -50,6 +51,7 @@ core_deps = [
|
||||
"markdown>=3.2.2,<4",
|
||||
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
|
||||
"netifaces>=0.11,<1",
|
||||
"passlib>=1.7.4,<2",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"pkginfo>=1.7.1,<2",
|
||||
"psutil>=5.8,<6",
|
||||
|
||||
+103
-59
@@ -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
|
||||
|
||||
@@ -18,6 +19,11 @@ from octoprint.util import atomic_write, deprecated, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import to_bytes, yaml
|
||||
|
||||
try:
|
||||
from passlib.hash import argon2 as passwordhash
|
||||
except ImportError:
|
||||
from passlib.hash import pbkdf2_sha256 as passwordhash
|
||||
|
||||
|
||||
class UserManager(GroupChangeListener):
|
||||
def __init__(self, group_manager, settings=None):
|
||||
@@ -127,29 +133,18 @@ class UserManager(GroupChangeListener):
|
||||
for session, user in list(self._session_users_by_session.items()):
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user.created + (24 * 60 * 60) < time.monotonic():
|
||||
if user.touched + (15 * 60) < time.monotonic():
|
||||
self._logger.info(
|
||||
"Cleaning up user session {} for user {}".format(
|
||||
session, user.get_id()
|
||||
)
|
||||
f"Cleaning up user session {session} for user {user.get_id()}"
|
||||
)
|
||||
self.logout_user(user, stale=True)
|
||||
|
||||
@staticmethod
|
||||
def create_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_password_hash(password, *args, **kwargs):
|
||||
return passwordhash.hash(password)
|
||||
|
||||
@staticmethod
|
||||
def create_legacy_password_hash(password, salt):
|
||||
return hashlib.sha512(
|
||||
to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)
|
||||
).hexdigest()
|
||||
@@ -159,23 +154,32 @@ class UserManager(GroupChangeListener):
|
||||
if not user:
|
||||
return False
|
||||
|
||||
hash = UserManager.create_password_hash(password, settings=self._settings)
|
||||
if user.check_password(hash):
|
||||
# new hash matches, correct password
|
||||
if user.check_password(password):
|
||||
# password matches, correct password
|
||||
return True
|
||||
else:
|
||||
# new hash doesn't match, but maybe the old one does, so check that!
|
||||
oldHash = UserManager.create_password_hash(
|
||||
password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", settings=self._settings
|
||||
# new hash doesn't match, check legacy hash
|
||||
salt = self._settings.get(["accessControl"], asdict=True, merged=True).get(
|
||||
"salt", None
|
||||
)
|
||||
if user.check_password(oldHash):
|
||||
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
|
||||
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)
|
||||
return True
|
||||
else:
|
||||
# old hash doesn't match either, wrong password
|
||||
# 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)
|
||||
|
||||
def add_user(self, username, password, active, permissions, groups, overwrite=False):
|
||||
pass
|
||||
|
||||
@@ -227,21 +231,28 @@ class UserManager(GroupChangeListener):
|
||||
del self._sessionids_by_userid[username]
|
||||
|
||||
def validate_user_session(self, userid, session):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
return userid == user.get_id()
|
||||
|
||||
return False
|
||||
|
||||
def find_user(self, userid=None, session=None):
|
||||
def find_user(self, userid=None, session=None, fresh=False):
|
||||
self._cleanup_sessions()
|
||||
|
||||
if session is not None and session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if userid is None or userid == user.get_id():
|
||||
user.touch()
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
def find_sessions_for(self, matcher):
|
||||
self._cleanup_sessions()
|
||||
|
||||
result = []
|
||||
for user in self.get_all_users():
|
||||
if matcher(user):
|
||||
@@ -249,7 +260,9 @@ class UserManager(GroupChangeListener):
|
||||
session_ids = self._sessionids_by_userid[user.get_id()]
|
||||
for session_id in session_ids:
|
||||
try:
|
||||
result.append(self._session_users_by_session[session_id])
|
||||
session_user = self._session_users_by_session[session_id]
|
||||
session_user.touch()
|
||||
result.append(session_user)
|
||||
except KeyError:
|
||||
# unknown session after all
|
||||
continue
|
||||
@@ -339,23 +352,6 @@ class UserManager(GroupChangeListener):
|
||||
|
||||
# TODO: Remove deprecated methods in OctoPrint 1.5.0
|
||||
|
||||
@staticmethod
|
||||
def createPasswordHash(*args, **kwargs):
|
||||
"""
|
||||
.. deprecated: 1.4.0
|
||||
|
||||
Replaced by :func:`~UserManager.create_password_hash`
|
||||
"""
|
||||
# we can't use the deprecated decorator here since this method is static
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"createPasswordHash has been renamed to create_password_hash",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return UserManager.create_password_hash(*args, **kwargs)
|
||||
|
||||
@deprecated(
|
||||
"changeUserRoles has been replaced by change_user_permissions",
|
||||
includedoc="Replaced by :func:`change_user_permissions`",
|
||||
@@ -489,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)
|
||||
|
||||
@@ -520,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
|
||||
@@ -567,6 +576,8 @@ class FilebasedUserManager(UserManager):
|
||||
if self._dirty:
|
||||
self._save()
|
||||
|
||||
self.cleanup_legacy_hashes()
|
||||
|
||||
self._customized = True
|
||||
else:
|
||||
self._customized = False
|
||||
@@ -575,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
|
||||
@@ -618,11 +629,11 @@ class FilebasedUserManager(UserManager):
|
||||
apikey=None,
|
||||
overwrite=False,
|
||||
):
|
||||
if not permissions:
|
||||
if permissions is None:
|
||||
permissions = []
|
||||
permissions = self._to_permissions(*permissions)
|
||||
|
||||
if not groups:
|
||||
if groups is None:
|
||||
groups = self._group_manager.default_groups
|
||||
groups = self._to_groups(*groups)
|
||||
|
||||
@@ -773,12 +784,40 @@ class FilebasedUserManager(UserManager):
|
||||
if username not in self._users:
|
||||
raise UnknownUser(username)
|
||||
|
||||
passwordHash = UserManager.create_password_hash(password, settings=self._settings)
|
||||
user = self._users[username]
|
||||
if user._passwordHash != passwordHash:
|
||||
user._passwordHash = passwordHash
|
||||
self._dirty = True
|
||||
self._save()
|
||||
user._passwordHash = UserManager.create_password_hash(password)
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
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)
|
||||
user = self._users[username]
|
||||
|
||||
return hashlib.sha512(
|
||||
to_bytes(username + user._passwordHash, encoding="utf-8", errors="replace")
|
||||
+ to_bytes(salt)
|
||||
).hexdigest()
|
||||
|
||||
def change_user_setting(self, username, key, value):
|
||||
if username not in self._users:
|
||||
@@ -845,10 +884,10 @@ class FilebasedUserManager(UserManager):
|
||||
self._dirty = True
|
||||
self._save()
|
||||
|
||||
def find_user(self, userid=None, apikey=None, session=None):
|
||||
def find_user(self, userid=None, apikey=None, session=None, fresh=False):
|
||||
user = UserManager.find_user(self, userid=userid, session=session)
|
||||
|
||||
if user is not None:
|
||||
if user is not None or (session and fresh):
|
||||
return user
|
||||
|
||||
if userid is not None:
|
||||
@@ -1126,8 +1165,14 @@ class User(UserMixin):
|
||||
"roles": self._roles,
|
||||
}
|
||||
|
||||
def check_password(self, passwordHash):
|
||||
return self._passwordHash == passwordHash
|
||||
def check_password(self, password, legacy=False):
|
||||
if legacy:
|
||||
return self._passwordHash == password
|
||||
|
||||
try:
|
||||
return passwordhash.verify(password, self._passwordHash)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
def get_id(self):
|
||||
return self.get_name()
|
||||
@@ -1383,8 +1428,7 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
wrapt.ObjectProxy.__init__(self, user)
|
||||
|
||||
self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes))
|
||||
self._self_created = time.monotonic()
|
||||
self._self_touched = time.monotonic()
|
||||
self._self_created = self._self_touched = time.monotonic()
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
|
||||
@@ -954,6 +954,12 @@ class LocalFileStorage(StorageInterface):
|
||||
source, destination, must_not_equal=True
|
||||
)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||
raise StorageError(
|
||||
f"{destination_data['name']} is an unrecognized file type",
|
||||
code=StorageError.INVALID_FILE,
|
||||
)
|
||||
|
||||
try:
|
||||
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
|
||||
except Exception as e:
|
||||
@@ -983,6 +989,12 @@ class LocalFileStorage(StorageInterface):
|
||||
source, destination
|
||||
)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(destination_data["name"]):
|
||||
raise StorageError(
|
||||
f"{destination_data['name']} is an unrecognized file type",
|
||||
code=StorageError.INVALID_FILE,
|
||||
)
|
||||
|
||||
# only a display rename? Update that and bail early
|
||||
if source_data["fullpath"] == destination_data["fullpath"]:
|
||||
self._set_display_metadata(destination_data)
|
||||
|
||||
@@ -1348,8 +1348,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
|
||||
@@ -1368,7 +1399,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))
|
||||
@@ -1401,6 +1432,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):
|
||||
"""
|
||||
@@ -1418,6 +1470,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)
|
||||
|
||||
@@ -1431,9 +1485,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")
|
||||
@@ -1482,6 +1541,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):
|
||||
"""
|
||||
|
||||
@@ -320,6 +320,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):
|
||||
@@ -370,7 +373,7 @@ class BackupPlugin(
|
||||
|
||||
def route_hook(self, *args, **kwargs):
|
||||
from octoprint.server import app
|
||||
from octoprint.server.util.flask import admin_validator
|
||||
from octoprint.server.util.flask import permission_validator
|
||||
from octoprint.server.util.tornado import (
|
||||
LargeResponseHandler,
|
||||
access_validation_factory,
|
||||
@@ -386,9 +389,15 @@ class BackupPlugin(
|
||||
"path": self.get_plugin_data_folder(),
|
||||
"as_attachment": True,
|
||||
"path_validation": path_validation_factory(
|
||||
lambda path: not is_hidden_path(path), status_code=404
|
||||
lambda path: not is_hidden_path(path)
|
||||
and self._match_backup_filename(
|
||||
os.path.basename(path), self._settings
|
||||
),
|
||||
status_code=404,
|
||||
),
|
||||
"access_validation": access_validation_factory(
|
||||
app, permission_validator, Permissions.PLUGIN_BACKUP_ACCESS
|
||||
),
|
||||
"access_validation": access_validation_factory(app, admin_validator),
|
||||
},
|
||||
)
|
||||
]
|
||||
@@ -1359,14 +1368,25 @@ class BackupPlugin(
|
||||
|
||||
@classmethod
|
||||
def _build_backup_filename(cls, settings):
|
||||
backup_prefix = cls._get_backup_prefix(settings)
|
||||
return "{}-backup-{}.zip".format(
|
||||
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _match_backup_filename(cls, path, settings):
|
||||
import re
|
||||
|
||||
backup_prefix = cls._get_backup_prefix(settings)
|
||||
return re.match(re.escape(backup_prefix) + r"-backup-\d{8}-\d{6}.zip", path)
|
||||
|
||||
@classmethod
|
||||
def _get_backup_prefix(cls, settings):
|
||||
if settings.global_get(["appearance", "name"]) == "":
|
||||
backup_prefix = "octoprint"
|
||||
else:
|
||||
backup_prefix = settings.global_get(["appearance", "name"])
|
||||
backup_prefix = sanitize(backup_prefix)
|
||||
return "{}-backup-{}.zip".format(
|
||||
backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT)
|
||||
)
|
||||
return sanitize(backup_prefix)
|
||||
|
||||
@classmethod
|
||||
def _restore_supported(cls, settings):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -18,10 +18,10 @@ from octoprint.util.version import (
|
||||
)
|
||||
|
||||
SENTRY_URL_SERVER = (
|
||||
"https://32fedab787cf4ef0abb9f4fb9060f7c5@o118517.ingest.sentry.io/1373987"
|
||||
"https://af30d06358144fb8af076ffd8984136d@o118517.ingest.sentry.io/1373987"
|
||||
)
|
||||
SENTRY_URL_COREUI = (
|
||||
"https://09c57ca82d4047b5a37bb0655ce14187@o118517.ingest.sentry.io/1374096"
|
||||
"https://e1d6b5d760f241408382d62a3e7fb416@o118517.ingest.sentry.io/1374096"
|
||||
)
|
||||
|
||||
SETTINGS_DEFAULTS = {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -228,7 +228,7 @@ class PluginManagerPlugin(
|
||||
"name": "List plugins",
|
||||
"description": gettext("Allows to list installed plugins."),
|
||||
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
|
||||
"roles": ["manage"],
|
||||
"roles": ["list"],
|
||||
},
|
||||
{
|
||||
"key": "MANAGE",
|
||||
@@ -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):
|
||||
|
||||
@@ -1471,6 +1471,9 @@ class SoftwareUpdatePlugin(
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
def is_blueprint_csrf_protected(self):
|
||||
return True
|
||||
|
||||
# ~~ Asset API
|
||||
|
||||
def get_assets(self):
|
||||
|
||||
@@ -53,3 +53,9 @@ class DevelConfig(BaseModel):
|
||||
|
||||
sockJsConnectTimeout: float = 30
|
||||
pluginTimings: bool = False
|
||||
|
||||
enableRateLimiter: bool = True
|
||||
"""Enable or disable the rate limiter. Careful, disabling this reduces security."""
|
||||
|
||||
enableCsrfProtection: bool = True
|
||||
"""Enable or disable the CSRF protection. Careful, disabling this reduces security."""
|
||||
@@ -141,8 +141,8 @@ class CookiesConfig(BaseModel):
|
||||
secure: bool = False
|
||||
"""Whether to set the `Secure` flag to true on cookies. Only set to true if you are running OctoPrint behind a reverse proxy taking care of SSL termination."""
|
||||
|
||||
samesite: Optional[SameSiteEnum] = None
|
||||
"""`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to unset. Be advised that many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482)."""
|
||||
samesite: Optional[SameSiteEnum] = "Strict"
|
||||
"""`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to `Strict`. Be advised that if forced unset, this has security implications as many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482)."""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -40,6 +40,7 @@ from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
import octoprint.filemanager
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
from octoprint.server import util
|
||||
@@ -126,10 +127,11 @@ from octoprint.printer.standard import Printer
|
||||
from octoprint.server.util import (
|
||||
corsRequestHandler,
|
||||
corsResponseHandler,
|
||||
csrfRequestHandler,
|
||||
loginFromApiKeyRequestHandler,
|
||||
requireLoginRequestHandler,
|
||||
)
|
||||
from octoprint.server.util.flask import PreemptiveCache
|
||||
from octoprint.server.util.flask import PreemptiveCache, validate_session_signature
|
||||
from octoprint.settings import settings
|
||||
|
||||
VERSION = __version__
|
||||
@@ -186,12 +188,25 @@ def load_user(id):
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if session and "usersession.signature" in session:
|
||||
sessionsig = session["usersession.signature"]
|
||||
else:
|
||||
sessionsig = ""
|
||||
|
||||
if sessionid:
|
||||
user = userManager.find_user(userid=id, session=sessionid)
|
||||
# session["_fresh"] is False if the session comes from a remember me cookie,
|
||||
# True if it came from a use of the login dialog
|
||||
user = userManager.find_user(
|
||||
userid=id, session=sessionid, fresh=session.get("_fresh", False)
|
||||
)
|
||||
else:
|
||||
user = userManager.find_user(userid=id)
|
||||
|
||||
if user and user.is_active:
|
||||
if (
|
||||
user
|
||||
and user.is_active
|
||||
and (not sessionid or validate_session_signature(sessionsig, id, sessionid))
|
||||
):
|
||||
return user
|
||||
|
||||
return None
|
||||
@@ -746,6 +761,15 @@ class Server:
|
||||
)
|
||||
}
|
||||
|
||||
only_known_types_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: octoprint.filemanager.valid_file_type(
|
||||
os.path.basename(path)
|
||||
),
|
||||
status_code=404,
|
||||
)
|
||||
}
|
||||
|
||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (
|
||||
octoprint.timelapse.valid_timelapse(path)
|
||||
or octoprint.timelapse.valid_timelapse_thumbnail(path)
|
||||
@@ -840,6 +864,7 @@ class Server:
|
||||
download_permission_validator,
|
||||
download_handler_kwargs,
|
||||
no_hidden_files_validator,
|
||||
only_known_types_validator,
|
||||
additional_mime_types,
|
||||
),
|
||||
),
|
||||
@@ -1355,7 +1380,9 @@ class Server:
|
||||
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
||||
app.config["REMEMBER_COOKIE_DURATION"] = 90 * 24 * 60 * 60 # 90 days
|
||||
app.config["REMEMBER_COOKIE_HTTPONLY"] = True
|
||||
# REMEMBER_COOKIE_SECURE will be taken care of by our custom cookie handling
|
||||
|
||||
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
|
||||
app.debug = self._debug
|
||||
@@ -1441,7 +1468,11 @@ class Server:
|
||||
|
||||
app.config["RATELIMIT_STRATEGY"] = "fixed-window-elastic-expiry"
|
||||
|
||||
limiter = Limiter(app, key_func=get_remote_address)
|
||||
limiter = Limiter(
|
||||
app,
|
||||
key_func=get_remote_address,
|
||||
enabled=s.getBoolean(["devel", "enableRateLimiter"]),
|
||||
)
|
||||
|
||||
def _setup_i18n(self, app):
|
||||
global babel
|
||||
@@ -1886,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,
|
||||
@@ -38,6 +39,7 @@ from octoprint.server.util.flask import (
|
||||
limit,
|
||||
no_firstrun_access,
|
||||
passive_login,
|
||||
session_signature,
|
||||
)
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
@@ -67,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
|
||||
@@ -312,6 +315,9 @@ def login():
|
||||
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.session
|
||||
session["usersession.signature"] = session_signature(
|
||||
username, user.session
|
||||
)
|
||||
g.user = user
|
||||
|
||||
login_user(user, remember=remember)
|
||||
|
||||
@@ -25,14 +25,14 @@ def get_permissions():
|
||||
|
||||
@api.route("/access/groups", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_groups():
|
||||
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
|
||||
|
||||
|
||||
@api.route("/access/groups", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def add_group():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -69,7 +69,7 @@ def add_group():
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_group(key):
|
||||
group = groupManager.find_group(key)
|
||||
if group is not None:
|
||||
@@ -80,7 +80,7 @@ def get_group(key):
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["PUT"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def update_group(key):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -113,7 +113,7 @@ def update_group(key):
|
||||
|
||||
@api.route("/access/groups/<key>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def remove_group(key):
|
||||
try:
|
||||
groupManager.remove_group(key)
|
||||
@@ -129,14 +129,14 @@ def remove_group(key):
|
||||
|
||||
@api.route("/access/users", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def get_users():
|
||||
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
|
||||
|
||||
|
||||
@api.route("/access/users", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def add_user():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
abort(400, description="Expected content-type JSON")
|
||||
@@ -188,7 +188,7 @@ def get_user(username):
|
||||
|
||||
@api.route("/access/users/<username>", methods=["PUT"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def update_user(username):
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
@@ -223,7 +223,7 @@ def update_user(username):
|
||||
|
||||
@api.route("/access/users/<username>", methods=["DELETE"])
|
||||
@no_firstrun_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
@Permissions.ADMIN.require(403)
|
||||
def remove_user(username):
|
||||
try:
|
||||
userManager.remove_user(username)
|
||||
@@ -243,7 +243,7 @@ def change_password_for_user(username):
|
||||
and not current_user.is_anonymous
|
||||
and (
|
||||
current_user.get_name() == username
|
||||
or current_user.has_permission(Permissions.SETTINGS)
|
||||
or current_user.has_permission(Permissions.ADMIN)
|
||||
)
|
||||
):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
@@ -257,7 +257,7 @@ def change_password_for_user(username):
|
||||
if "password" not in data or not data["password"]:
|
||||
abort(400, description="new password is missing")
|
||||
|
||||
if not current_user.has_permission(Permissions.SETTINGS) or "current" in data:
|
||||
if not current_user.has_permission(Permissions.ADMIN) or "current" in data:
|
||||
if "current" not in data or not data["current"]:
|
||||
abort(400, description="current password is missing")
|
||||
|
||||
|
||||
@@ -610,6 +610,15 @@ def uploadGcodeFile(target):
|
||||
):
|
||||
abort(409, description="File already exists and noOverwrite was set")
|
||||
|
||||
if (
|
||||
fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)
|
||||
and not Permissions.FILES_DELETE.can()
|
||||
):
|
||||
abort(
|
||||
403,
|
||||
description="File already exists, cannot overwrite due to a lack of permissions",
|
||||
)
|
||||
|
||||
reselect = printer.is_current_file(futureFullPathInStorage, sd)
|
||||
|
||||
user = current_user.get_name()
|
||||
@@ -1135,42 +1144,55 @@ def gcodeFileCommand(filename, target):
|
||||
if not (is_file or is_folder):
|
||||
abort(400, description=f"Neither file nor folder, can't {command}")
|
||||
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
elif command == "move":
|
||||
with Permissions.FILES_DELETE.require(403):
|
||||
if _isBusy(target, filename):
|
||||
abort(
|
||||
409,
|
||||
description="Trying to move a file or folder that is currently in use",
|
||||
)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (
|
||||
_verifyFileExists(target, destination)
|
||||
or _verifyFolderExists(target, destination)
|
||||
) and sanitized_destination != filename:
|
||||
try:
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
fileManager.copy_folder(target, filename, destination)
|
||||
|
||||
elif command == "move":
|
||||
with Permissions.FILES_DELETE.require(403):
|
||||
if _isBusy(target, filename):
|
||||
abort(
|
||||
409,
|
||||
description="Trying to move a file or folder that is currently in use",
|
||||
)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
if (
|
||||
_verifyFileExists(target, destination)
|
||||
or _verifyFolderExists(target, destination)
|
||||
) and sanitized_destination != filename:
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselect_file()
|
||||
|
||||
if is_file:
|
||||
fileManager.move_file(target, filename, destination)
|
||||
else:
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||
abort(
|
||||
415,
|
||||
description=f"Could not {command} {filename} to {destination}, invalid type",
|
||||
)
|
||||
else:
|
||||
abort(
|
||||
500,
|
||||
description=f"Could not {command} {filename} to {destination}",
|
||||
)
|
||||
|
||||
location = url_for(
|
||||
".readGcodeFile",
|
||||
|
||||
@@ -174,7 +174,8 @@ def deleteInstalledLanguagePack(locale, pack):
|
||||
def _unpack_uploaded_zipfile(path, target):
|
||||
with zipfile.ZipFile(path, "r") as zip:
|
||||
# sanity check
|
||||
map(_validate_archive_name, zip.namelist())
|
||||
for info in zip.infolist():
|
||||
_validate_zip_info(info, target)
|
||||
|
||||
# unpack everything
|
||||
zip.extractall(target)
|
||||
@@ -183,16 +184,27 @@ def _unpack_uploaded_zipfile(path, target):
|
||||
def _unpack_uploaded_tarball(path, target):
|
||||
with tarfile.open(path, "r") as tar:
|
||||
# sanity check
|
||||
map(_validate_archive_name, tar.getmembers())
|
||||
for info in tar.getmembers():
|
||||
_validate_tar_info(info, target)
|
||||
|
||||
# unpack everything
|
||||
tar.extractall(target)
|
||||
|
||||
|
||||
def _validate_archive_name(name):
|
||||
if name.startswith("/") or ".." in name:
|
||||
def _validate_archive_name(name, target):
|
||||
if not os.path.abspath(os.path.join(target, name)).startswith(target + os.path.sep):
|
||||
raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}")
|
||||
|
||||
|
||||
def _validate_zip_info(info, target):
|
||||
_validate_archive_name(info.filename, target)
|
||||
|
||||
|
||||
def _validate_tar_info(info, target):
|
||||
_validate_archive_name(info.name, target)
|
||||
if not (info.isfile() or info.isdir()):
|
||||
raise InvalidLanguagePack("Provided language pack contains invalid file type")
|
||||
|
||||
|
||||
class InvalidLanguagePack(Exception):
|
||||
pass
|
||||
@@ -18,8 +18,7 @@ from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
# ~~ settings
|
||||
|
||||
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
|
||||
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
|
||||
FOLDER_TYPES = ("uploads", "timelapse", "watched")
|
||||
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
@@ -269,8 +268,6 @@ def getSettings():
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
"timelapse": s.getBaseFolder("timelapse"),
|
||||
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
||||
"logs": s.getBaseFolder("logs"),
|
||||
"watched": s.getBaseFolder("watched"),
|
||||
},
|
||||
"temperature": {
|
||||
@@ -464,10 +461,7 @@ def _saveSettings(data):
|
||||
|
||||
if "folder" in data:
|
||||
try:
|
||||
folders = {
|
||||
FOLDER_MAPPING.get(folder, folder): path
|
||||
for folder, path in data["folder"].items()
|
||||
}
|
||||
folders = data["folder"]
|
||||
future = {}
|
||||
for folder in FOLDER_TYPES:
|
||||
future[folder] = s.getBaseFolder(folder)
|
||||
|
||||
@@ -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
|
||||
@@ -5,11 +5,13 @@ __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 functools
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Union
|
||||
|
||||
import flask
|
||||
@@ -24,6 +26,9 @@ import tornado.web
|
||||
import webassets.updater
|
||||
import webassets.utils
|
||||
from cachelib import BaseCache
|
||||
from flask import current_app
|
||||
from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
|
||||
from flask_login.utils import decode_cookie, encode_cookie
|
||||
from werkzeug.local import LocalProxy
|
||||
from werkzeug.utils import cached_property
|
||||
|
||||
@@ -457,6 +462,49 @@ class ReverseProxiedEnvironment:
|
||||
# ~~ request and response versions
|
||||
|
||||
|
||||
def encode_remember_me_cookie(value):
|
||||
from octoprint.server import userManager
|
||||
|
||||
name = value.split("|")[0]
|
||||
try:
|
||||
remember_key = userManager.signature_key_for_user(
|
||||
name, salt=current_app.config["SECRET_KEY"]
|
||||
)
|
||||
timestamp = datetime.utcnow().timestamp()
|
||||
return encode_cookie(f"{name}|{timestamp}", key=remember_key)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def decode_remember_me_cookie(value):
|
||||
from octoprint.server import userManager
|
||||
|
||||
parts = value.split("|")
|
||||
if len(parts) == 3:
|
||||
name, created, _ = parts
|
||||
|
||||
try:
|
||||
# valid signature?
|
||||
signature_key = userManager.signature_key_for_user(
|
||||
name, salt=current_app.config["SECRET_KEY"]
|
||||
)
|
||||
cookie = decode_cookie(value, key=signature_key)
|
||||
if cookie:
|
||||
# still valid?
|
||||
if (
|
||||
datetime.fromtimestamp(float(created))
|
||||
+ timedelta(seconds=current_app.config["REMEMBER_COOKIE_DURATION"])
|
||||
> datetime.utcnow()
|
||||
):
|
||||
return encode_cookie(name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raise ValueError("Invalid remember me cookie")
|
||||
|
||||
|
||||
class OctoPrintFlaskRequest(flask.Request):
|
||||
environment_wrapper = staticmethod(lambda x: x)
|
||||
|
||||
@@ -472,10 +520,23 @@ class OctoPrintFlaskRequest(flask.Request):
|
||||
result = {}
|
||||
desuffixed = {}
|
||||
for key, value in cookies.items():
|
||||
if key.endswith(self.cookie_suffix):
|
||||
desuffixed[key[: -len(self.cookie_suffix)]] = value
|
||||
else:
|
||||
result[key] = value
|
||||
|
||||
def process_value(k, v):
|
||||
if k == current_app.config.get(
|
||||
"REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME
|
||||
):
|
||||
return decode_remember_me_cookie(v)
|
||||
return v
|
||||
|
||||
try:
|
||||
if key.endswith(self.cookie_suffix):
|
||||
key = key[: -len(self.cookie_suffix)]
|
||||
desuffixed[key] = process_value(key, value)
|
||||
else:
|
||||
result[key] = process_value(key, value)
|
||||
except ValueError:
|
||||
# ignore broken cookies
|
||||
pass
|
||||
|
||||
result.update(desuffixed)
|
||||
return result
|
||||
@@ -506,7 +567,7 @@ class OctoPrintFlaskRequest(flask.Request):
|
||||
|
||||
|
||||
class OctoPrintFlaskResponse(flask.Response):
|
||||
def set_cookie(self, key, *args, **kwargs):
|
||||
def set_cookie(self, key, value="", *args, **kwargs):
|
||||
# restrict cookie path to script root
|
||||
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
|
||||
|
||||
@@ -525,9 +586,13 @@ class OctoPrintFlaskResponse(flask.Response):
|
||||
# set secure if necessary
|
||||
kwargs["secure"] = settings().getBoolean(["server", "cookies", "secure"])
|
||||
|
||||
# tie account properties to remember me cookie (e.g. current password hash)
|
||||
if key == current_app.config.get("REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME):
|
||||
value = encode_remember_me_cookie(value)
|
||||
|
||||
# add request specific cookie suffix to name
|
||||
flask.Response.set_cookie(
|
||||
self, key + flask.request.cookie_suffix, *args, **kwargs
|
||||
self, key + flask.request.cookie_suffix, value=value, *args, **kwargs
|
||||
)
|
||||
|
||||
def delete_cookie(self, key, path="/", domain=None):
|
||||
@@ -643,6 +708,9 @@ def passive_login():
|
||||
)
|
||||
if hasattr(u, "session"):
|
||||
flask.session["usersession.id"] = u.session
|
||||
flask.session["usersession.signature"] = session_signature(
|
||||
u.get_id(), u.session
|
||||
)
|
||||
flask.g.user = u
|
||||
|
||||
eventManager().fire(Events.USER_LOGGED_IN, payload={"username": u.get_id()})
|
||||
@@ -1868,3 +1936,19 @@ class OctoPrintJsonProvider(flask.json.provider.DefaultJSONProvider):
|
||||
return JsonEncoding.encode(object_)
|
||||
except TypeError:
|
||||
return flask.json.provider.DefaultJSONProvider.default(object_)
|
||||
|
||||
|
||||
##~~ Session signing
|
||||
|
||||
|
||||
def session_signature(user, session):
|
||||
from octoprint.server import userManager
|
||||
|
||||
key = userManager.signature_key_for_user(user, salt=current_app.config["SECRET_KEY"])
|
||||
return hmac.new(
|
||||
key.encode("utf-8"), session.encode("utf-8"), hashlib.sha512
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def validate_session_signature(sig, user, session):
|
||||
return hmac.compare_digest(sig, session_signature(user, session))
|
||||
@@ -21,9 +21,10 @@ import octoprint.vendor.sockjs.tornado.session
|
||||
import octoprint.vendor.sockjs.tornado.util
|
||||
from octoprint.access.groups import GroupChangeListener
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.access.users import LoginStatusListener
|
||||
from octoprint.access.users import LoginStatusListener, SessionUser
|
||||
from octoprint.events import Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import RepeatedTimer
|
||||
from octoprint.util.json import dumps as json_dumps
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
@@ -173,6 +174,10 @@ class PrinterStateConnection(
|
||||
self._subscriptions_active = False
|
||||
self._subscriptions = {"state": False, "plugins": [], "events": []}
|
||||
|
||||
self._keep_alive = RepeatedTimer(
|
||||
60, self._keep_alive_callback, condition=lambda: self._authed
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_remote_address(info):
|
||||
forwarded_for = info.headers.get("X-Forwarded-For")
|
||||
@@ -180,6 +185,13 @@ class PrinterStateConnection(
|
||||
return forwarded_for.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def _keep_alive_callback(self):
|
||||
if not self._authed:
|
||||
return
|
||||
if not isinstance(self._user, SessionUser):
|
||||
return
|
||||
self._user.touch()
|
||||
|
||||
def __str__(self):
|
||||
if self._remoteAddress:
|
||||
return f"{self!r} connected to {self._remoteAddress}"
|
||||
@@ -442,12 +454,17 @@ class PrinterStateConnection(
|
||||
{
|
||||
"serverTime": time.time(),
|
||||
"temps": temperatures,
|
||||
"logs": self._filter_logs(logs),
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
"markings": list(self._printer.get_markings()),
|
||||
}
|
||||
)
|
||||
if self._user.has_permission(Permissions.MONITOR_TERMINAL):
|
||||
data.update(
|
||||
{
|
||||
"logs": self._filter_logs(logs),
|
||||
"messages": messages,
|
||||
}
|
||||
)
|
||||
self._emit("current", payload=data)
|
||||
|
||||
def on_printer_send_initial_data(self, data):
|
||||
@@ -457,9 +474,13 @@ class PrinterStateConnection(
|
||||
return
|
||||
|
||||
data_to_send = dict(data)
|
||||
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
|
||||
data_to_send["messages"] = self._filter_messages(data_to_send.get("messages", []))
|
||||
|
||||
data_to_send["serverTime"] = time.time()
|
||||
if self._user.has_permission(Permissions.MONITOR_TERMINAL):
|
||||
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
|
||||
data_to_send["messages"] = self._filter_messages(
|
||||
data_to_send.get("messages", [])
|
||||
)
|
||||
self._emit("history", payload=data_to_send)
|
||||
|
||||
def _filter_state_subscription(self, sub, values):
|
||||
@@ -716,6 +737,8 @@ class PrinterStateConnection(
|
||||
)
|
||||
self._authed = True
|
||||
|
||||
self._keep_alive.start()
|
||||
|
||||
for name, hook in self._authed_hooks.items():
|
||||
try:
|
||||
hook(self, self._user)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -511,6 +511,7 @@ class Settings:
|
||||
"logs",
|
||||
]
|
||||
)
|
||||
self.warn_about_risky_settings()
|
||||
|
||||
def _init_basedir(self, basedir):
|
||||
if basedir is not None:
|
||||
@@ -543,6 +544,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")
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -862,7 +862,7 @@ $(function () {
|
||||
access.onUserLoggedIn =
|
||||
access.onUserLoggedOut =
|
||||
function (user) {
|
||||
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
|
||||
if (access.loginState.hasPermission(access.permissions.ADMIN)) {
|
||||
access.groups.requestData().done(function () {
|
||||
access.users.requestData();
|
||||
});
|
||||
|
||||
@@ -1622,9 +1622,7 @@ $(function () {
|
||||
);
|
||||
$("p, form", self.uploadExistsDialog).toggle(!fileSizeTooBig);
|
||||
$("span", self.uploadExistsDialog).toggle(fileSizeTooBig);
|
||||
$("input", self.uploadExistsDialog)
|
||||
.val("")
|
||||
.prop("placeholder", response.suggestion);
|
||||
$("input", self.uploadExistsDialog).val(response.suggestion);
|
||||
$("a.upload-rename", self.uploadExistsDialog)
|
||||
.toggle(!fileSizeTooBig)
|
||||
.prop("disabled", false)
|
||||
@@ -1634,7 +1632,6 @@ $(function () {
|
||||
"input",
|
||||
self.uploadExistsDialog
|
||||
).val();
|
||||
if (newName === "") newName = response.suggestion;
|
||||
|
||||
OctoPrint.files
|
||||
.exists("local", path, newName)
|
||||
@@ -1668,13 +1665,22 @@ $(function () {
|
||||
}
|
||||
});
|
||||
});
|
||||
$("a.upload-overwrite", self.uploadExistsDialog)
|
||||
.off("click")
|
||||
.on("click", function () {
|
||||
self.uploadExistsDialog.modal("hide");
|
||||
data.formData = formData;
|
||||
data.submit();
|
||||
});
|
||||
if (
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.FILES_DELETE
|
||||
)
|
||||
) {
|
||||
$("a.upload-overwrite", self.uploadExistsDialog)
|
||||
.off("click")
|
||||
.show()
|
||||
.on("click", function () {
|
||||
self.uploadExistsDialog.modal("hide");
|
||||
data.formData = formData;
|
||||
data.submit();
|
||||
});
|
||||
} else {
|
||||
$("a.upload-overwrite", self.uploadExistsDialog).hide();
|
||||
}
|
||||
self.uploadExistsDialog.modal("show");
|
||||
} else {
|
||||
data.formData = formData;
|
||||
|
||||
@@ -255,8 +255,6 @@ $(function () {
|
||||
|
||||
self.folder_uploads = ko.observable(undefined);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
self.folder_timelapseTmp = ko.observable(undefined);
|
||||
self.folder_logs = ko.observable(undefined);
|
||||
self.folder_watched = ko.observable(undefined);
|
||||
|
||||
self.scripts_gcode_beforePrintStarted = ko.observable(undefined);
|
||||
@@ -344,7 +342,7 @@ $(function () {
|
||||
self.server_onlineCheckResolutionBroken(false);
|
||||
};
|
||||
|
||||
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
|
||||
var folderTypes = ["uploads", "timelapse", "watched"];
|
||||
|
||||
var checkForDuplicateFolders = function () {
|
||||
_.each(folderTypes, function (folderType) {
|
||||
@@ -772,7 +770,6 @@ $(function () {
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function (e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
|
||||
@@ -225,6 +225,8 @@ $(function () {
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function (data) {
|
||||
if (!data) return;
|
||||
|
||||
var length = self.log().length;
|
||||
if (length >= self.upperLimit()) {
|
||||
return;
|
||||
@@ -276,6 +278,8 @@ $(function () {
|
||||
};
|
||||
|
||||
self._processHistoryLogData = function (data) {
|
||||
if (!data) return;
|
||||
|
||||
self.plainLogLines(data);
|
||||
self.log(_.map(data, self._toInternalFormat));
|
||||
self.updateOutput();
|
||||
|
||||
@@ -88,7 +88,7 @@ $(function () {
|
||||
|
||||
self.userSettingsDialog.trigger("beforeSave");
|
||||
|
||||
function process() {
|
||||
function saveSettings() {
|
||||
var settings = {
|
||||
interface: {
|
||||
language: self.interface_language()
|
||||
@@ -110,7 +110,7 @@ $(function () {
|
||||
self.access_currentPassword()
|
||||
)
|
||||
.done(function () {
|
||||
process();
|
||||
saveSettings();
|
||||
})
|
||||
.fail(function (xhr) {
|
||||
if (xhr.status === 403) {
|
||||
@@ -118,7 +118,7 @@ $(function () {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
process();
|
||||
saveSettings();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
<div data-bind="visible: languagePacksAvailable()">
|
||||
<div id="settings_appearance_managelanguagesdialog_list" data-bind="foreach: translations.paginatedItems">
|
||||
<div class="entry">
|
||||
<strong><a href="#" class="fas" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fas fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
|
||||
<strong><a href="#" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fas fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
|
||||
<div class="packs">
|
||||
<!-- ko foreach: $data.packs -->
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -20,26 +20,6 @@
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.timelapseTmp, success: testFolderConfigSuccess.timelapseTmp}">
|
||||
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_timelapseTmp, valueUpdate: 'input'" id="settings-folderTimelapseTemp">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapseTmp'); }, enable: folder_timelapseTmp() && !testFolderConfigBusy(), css: {disabled: !folder_timelapseTmp() || testFolderConfigBusy()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapseTmp() || testFolderConfigOk.timelapseTmp(), text: testFolderConfigText.timelapseTmp"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.logs, success: testFolderConfigSuccess.logs}">
|
||||
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append input-block-level">
|
||||
<input type="text" data-bind="value: folder_logs, valueUpdate: 'input'" id="settings-folderLogs">
|
||||
<a class="btn add-on" data-bind="click: function() { testFolderConfig('logs'); }, enable: folder_logs() && !testFolderConfigBusy(), css: {disabled: !folder_logs() || testFolderConfigBusy()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: testFolderConfigBroken.logs() || testFolderConfigOk.logs(), text: testFolderConfigText.logs"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: testFolderConfigError.watched, success: testFolderConfigSuccess.watched}">
|
||||
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
|
||||
<div class="controls">
|
||||
@@ -65,6 +45,11 @@
|
||||
{% endtrans %}
|
||||
</div>
|
||||
|
||||
<p>{% trans %}
|
||||
Please note: Not all of the folders used by OctoPrint can be configured through the UI, only those most commonly moved to other places. If you need to configure other folders,
|
||||
please do so by manually editing the configuration. See the docs for details.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||
|
||||
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
||||
|
||||
@@ -24,6 +24,9 @@
|
||||
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p>{% trans %}
|
||||
Please note that you will be <strong>logged out immediately</strong> after changing your password and asked to login again.
|
||||
{% endtrans %}</p>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('API Key') }}</legend>
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
@@ -10,6 +10,7 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import flask
|
||||
from ddt import data, ddt, unpack
|
||||
|
||||
from octoprint.server.util.flask import (
|
||||
@@ -424,6 +425,9 @@ class OctoPrintFlaskRequestTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.orig_environment_wrapper = OctoPrintFlaskRequest.environment_wrapper
|
||||
|
||||
self.app = flask.Flask("testapp")
|
||||
self.app.config["SECRET_KEY"] = "secret"
|
||||
|
||||
def tearDown(self):
|
||||
OctoPrintFlaskRequest.environment_wrapper = staticmethod(
|
||||
self.orig_environment_wrapper
|
||||
@@ -470,7 +474,8 @@ class OctoPrintFlaskRequestTest(unittest.TestCase):
|
||||
|
||||
request = OctoPrintFlaskRequest(environ)
|
||||
|
||||
cookies = request.cookies
|
||||
with self.app.app_context():
|
||||
cookies = request.cookies
|
||||
self.assertDictEqual(
|
||||
{
|
||||
"postfixed": "postfixed_value",
|
||||
@@ -495,6 +500,9 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
||||
self.settings = mock.MagicMock()
|
||||
self.settings_getter.return_value = self.settings
|
||||
|
||||
self.app = flask.Flask("testapp")
|
||||
self.app.config["SECRET_KEY"] = "secret"
|
||||
|
||||
def tearDown(self):
|
||||
self.settings_patcher.stop()
|
||||
|
||||
@@ -545,13 +553,14 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
||||
|
||||
# test set_cookie
|
||||
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
||||
response.set_cookie("some_key", "some_value", **kwargs)
|
||||
with self.app.app_context():
|
||||
response.set_cookie("some_key", "some_value", **kwargs)
|
||||
|
||||
# set_cookie should have key and path values adjusted
|
||||
set_cookie_mock.assert_called_once_with(
|
||||
response,
|
||||
"some_key" + expected_suffix,
|
||||
"some_value",
|
||||
value="some_value",
|
||||
path=expected_path_set,
|
||||
secure=secure,
|
||||
samesite=expected_samesite,
|
||||
@@ -560,7 +569,8 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
|
||||
# test delete_cookie
|
||||
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
|
||||
with mock.patch("flask.Response.delete_cookie") as delete_cookie_mock:
|
||||
response.delete_cookie("some_key", **kwargs)
|
||||
with self.app.app_context():
|
||||
response.delete_cookie("some_key", **kwargs)
|
||||
|
||||
# delete_cookie internally calls set_cookie - so our delete_cookie call still uses the non modified
|
||||
# key and path values, set_cookie will translate those (as tested above)
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+597
-578
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user