├── MANIFEST.in ├── .gitignore ├── babel.cfg ├── requirements.txt ├── .scrutinizer.yml ├── octoprint_auth_ldap ├── .editorconfig ├── __init__.py ├── constants.py ├── user.py ├── group.py ├── tweaks.py ├── ldap.py ├── plugin.py ├── templates │ └── auth_ldap_settings.jinja2 ├── group_manager.py └── user_manager.py ├── pylintrc ├── .github └── workflows │ └── pythonpackage.yml ├── setup.py ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include requirements.txt -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | .idea 4 | *.iml 5 | build 6 | dist 7 | *.egg* 8 | .DS_Store 9 | -------------------------------------------------------------------------------- /babel.cfg: -------------------------------------------------------------------------------- 1 | [python: */**.py] 2 | [jinja2: */**.jinja2] 3 | extensions=jinja2.ext.autoescape, jinja2.ext.with_ 4 | 5 | [javascript: */**.js] 6 | extract_messages = gettext, ngettext 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ### 2 | # This file is only here to make sure that something like 3 | # 4 | # pip install -e . 5 | # 6 | # works as expected. Requirements can be found in setup.py. 7 | ### 8 | -------------------------------------------------------------------------------- /.scrutinizer.yml: -------------------------------------------------------------------------------- 1 | checks: 2 | python: 3 | code_rating: true 4 | duplicate_code: true 5 | typecheck_maybe_no_member: true 6 | classes_valid_slots: true 7 | basic_missing_reversed_argument: true 8 | 9 | build: 10 | environment: 11 | python: 12 | version: 3.7.1 13 | virtualenv: true 14 | apt_packages: 15 | - python-dev 16 | - libldap2-dev 17 | - libsasl2-dev 18 | - libssl-dev 19 | nodes: 20 | analysis: 21 | project_setup: 22 | override: 23 | - 'true' 24 | tests: 25 | override: 26 | - py-scrutinizer-run 27 | - pylint-run 28 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | ij_visual_guides = 80, 120 11 | ij_wrap_on_typing = true 12 | ij_continuation_indent_size = 4 13 | ij_smart_tabs = true 14 | ij_any_if_brace_force = always 15 | ij_any_for_brace_force = always 16 | ij_any_while_brace_force = always 17 | 18 | [*.py] 19 | indent_style = space 20 | indent_size = 4 21 | 22 | [*.js] 23 | indent_size = 2 24 | ij_continuation_indent_size = 2 25 | 26 | [*.md] 27 | indent_size = 2 28 | trim_trailing_whitespace = false 29 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | from octoprint_auth_ldap.plugin import AuthLDAPPlugin 5 | 6 | __plugin_name__ = "Auth LDAP" 7 | __plugin_pythoncompat__ = ">=2.7,<4" 8 | 9 | 10 | def __plugin_load__(): 11 | # noinspection PyGlobalUndefined 12 | global __plugin_implementation__ 13 | __plugin_implementation__ = AuthLDAPPlugin() 14 | 15 | # noinspection PyGlobalUndefined 16 | global __plugin_hooks__ 17 | __plugin_hooks__ = { 18 | "octoprint.access.users.factory": __plugin_implementation__.ldap_user_factory, 19 | "octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.check_config 20 | } 21 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/constants.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | # settings keys 4 | # DO NOT CHANGE without updating AuthLDAPPlugin.on_settings_migrate() 5 | AUTH_PASSWORD = "auth_password" 6 | AUTH_PASSWORD_FILE = "auth_password_file" 7 | AUTH_USER = "auth_user" 8 | DEFAULT_ADMIN_GROUP = "default_admin_group" 9 | DEFAULT_USER_GROUP = "default_user_group" 10 | LDAP_GROUP_KEY_PREFIX = "ldap_group_key_prefix" 11 | LDAP_PARENT_GROUP_KEY = "ldap_parent_group_key" 12 | LDAP_PARENT_GROUP_DESCRIPTION = "ldap_parent_group_description" 13 | LDAP_PARENT_GROUP_NAME = "ldap_parent_group_name" 14 | OU_FILTER = "ou_filter" 15 | OU_MEMBER_FILTER = "ou_member_filter" 16 | OU = "ou" 17 | LOCAL_CACHE = "local_cache", 18 | REQUEST_TLS_CERT = "request_tls_cert" 19 | SEARCH_BASE = "search_base" 20 | SEARCH_FILTER = "search_filter" 21 | SEARCH_TERM_TRANSFORM = "search_term_transform" 22 | URI = "uri" 23 | USERID_FIELD = "userid_field" 24 | USERID_PATTERN = "userid_pattern" 25 | 26 | # frequently used terms 27 | DISTINGUISHED_NAME = "dn" 28 | 29 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/user.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | from octoprint.access.users import User 5 | 6 | 7 | class LDAPUser(User): 8 | USER_TYPE = "LDAP" 9 | 10 | # noinspection PyShadowingNames 11 | def __init__( 12 | self, 13 | username, 14 | passwordHash=None, 15 | active=True, 16 | permissions=None, 17 | groups=None, 18 | apikey=None, 19 | settings=None, 20 | dn=None 21 | ): 22 | User.__init__( 23 | self, 24 | username=username, 25 | passwordHash=passwordHash, 26 | active=active, 27 | permissions=permissions, 28 | groups=groups, 29 | apikey=apikey, 30 | settings=settings 31 | ) 32 | # TODO validate distinguished name 33 | self._dn = dn 34 | 35 | @property 36 | def distinguished_name(self): 37 | return self._dn 38 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | 3 | disable= 4 | 5 | enable=zip-builtin-not-iterating,xrange-builtin,using-cmp-argument,unpacking-in-except,unicode-builtin,unichr-builtin,sys-max-int,standarderror-builtin,setslice-method,round-builtin,reload-builtin,reduce-builtin,rdiv-method,raw-input-builtin,range-builtin-not-iterating,raising-string,print-statement,parameter-unpacking,old-raise-syntax,old-octal-literal,old-ne-operator,old-division,oct-method,nonzero-method,no-absolute-import,next-method-called,metaclass-assignment,map-builtin-not-iterating,long-suffix,long-builtin,invalid-str-codec,intern-builtin,input-builtin,indexing-exception,import-star-module-level,idiv-method,hex-method,getslice-method,filter-builtin-not-iterating,file-builtin,execfile-builtin,exception-message-attribute,eq-without-hash,div-method,dict-view-method,dict-iter-method,deprecated-string-function,deprecated-str-translate-call,delslice-method,coerce-method,coerce-builtin,cmp-method,cmp-builtin,buffer-builtin,basestring-builtin,bad-python3-import,backtick,apply-builtin -------------------------------------------------------------------------------- /.github/workflows/pythonpackage.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | python-version: [2.7, 3.5, 3.6, 3.7] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | pip install -r requirements.txt 24 | - name: Lint with flake8 25 | run: | 26 | pip install flake8 27 | # stop the build if there are Python syntax errors or undefined names 28 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 29 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 30 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 31 | 32 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/group.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | from octoprint.access.groups import Group 5 | 6 | 7 | class LDAPGroup(Group): 8 | GROUP_TYPE = "LDAP" 9 | 10 | def __init__( 11 | self, 12 | key, 13 | name, 14 | description="", 15 | permissions=None, 16 | subgroups=None, 17 | default=False, 18 | removable=True, 19 | changeable=True, 20 | toggleable=True, 21 | dn=None 22 | ): 23 | Group.__init__( 24 | self, 25 | key=key, 26 | name=name, 27 | description=description, 28 | permissions=permissions, 29 | subgroups=subgroups, 30 | default=default, 31 | removable=removable, 32 | changeable=changeable, 33 | toggleable=toggleable 34 | ) 35 | # TODO validate distinguished name 36 | self._dn = dn 37 | 38 | @property 39 | def distinguished_name(self): 40 | return self._dn 41 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/tweaks.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | import logging 5 | 6 | from octoprint.plugin import SettingsPlugin as OctoPrintSettingPlugin 7 | 8 | 9 | class SettingsPlugin(OctoPrintSettingPlugin): 10 | @property 11 | def settings(self): 12 | return self._settings 13 | 14 | @property 15 | def identifier(self): 16 | return self._identifier 17 | 18 | @property 19 | def logger(self): 20 | if "_logger" in self.__dict__: 21 | return self._logger 22 | else: 23 | # FIXME vexingly, sometimes we want to log things before the logger is injected 24 | return logging.getLogger("octoprint.plugins.auth_ldap") 25 | 26 | 27 | class DependentOnSettingsPlugin: 28 | def __init__(self, plugin): 29 | self._plugin = plugin 30 | 31 | @property 32 | def plugin(self): 33 | return self._plugin 34 | 35 | @property 36 | def logger(self): 37 | return self._plugin.logger 38 | 39 | @property 40 | def settings(self): 41 | return self._plugin.settings 42 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/ldap.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | import json 5 | 6 | import ldap 7 | from octoprint_auth_ldap.constants import AUTH_PASSWORD, AUTH_PASSWORD_FILE, AUTH_USER, DISTINGUISHED_NAME, OU, OU_FILTER, OU_MEMBER_FILTER, \ 8 | REQUEST_TLS_CERT, SEARCH_BASE, URI 9 | from octoprint_auth_ldap.tweaks import DependentOnSettingsPlugin 10 | from pathlib import Path 11 | 12 | 13 | class LDAPConnection(DependentOnSettingsPlugin): 14 | def __init__(self, plugin): 15 | DependentOnSettingsPlugin.__init__(self, plugin) 16 | 17 | def get_client(self, user=None, password=None): 18 | uri = self.settings.get([URI]) 19 | if not uri: 20 | self.logger.debug("No LDAP URI") 21 | return None 22 | 23 | if not user: 24 | user = self.settings.get([AUTH_USER]) 25 | password = self.settings.get([AUTH_PASSWORD]) or \ 26 | Path(self.settings.get([AUTH_PASSWORD_FILE])).read_text() 27 | 28 | try: 29 | self.logger.debug("Initializing LDAP connection to %s" % uri) 30 | client = ldap.initialize(uri) 31 | if self.settings.get([REQUEST_TLS_CERT]): 32 | self.logger.debug("Requesting TLS certificate") 33 | client.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) 34 | else: 35 | client.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) 36 | if user is not None: 37 | self.logger.debug("Binding to LDAP as %s" % user) 38 | client.bind_s(user, password) 39 | return client 40 | except ldap.INVALID_CREDENTIALS: 41 | self.logger.error("Invalid credentials to bind to LDAP as %s" % user) 42 | except ldap.SERVER_DOWN as e: 43 | self.logger.error("the server at %s is down" % uri ) 44 | except ldap.LDAPError as e: 45 | self.logger.error(json.dumps(e)) 46 | return None 47 | 48 | def search(self, ldap_filter, base=None, scope=ldap.SCOPE_SUBTREE): 49 | if not base: 50 | base = self.settings.get([SEARCH_BASE]) 51 | try: 52 | client = self.get_client() 53 | if client is not None: 54 | # self.logger.debug("Searching LDAP, base: %s and filter: %s" % (base, ldap_filter)) 55 | result = client.search_s(base, scope, ldap_filter) 56 | client.unbind_s() 57 | if result: 58 | dn, data = result[0] 59 | """ 60 | # Dump LDAP search query results to logger 61 | self.logger.debug("dn: %s" % dn) 62 | for key, value in data.items(): 63 | self.logger.debug("%s: %s" % (key, value)) 64 | """ 65 | return dict(dn=dn, data=data) 66 | except ldap.LDAPError as e: 67 | self.logger.error(json.dumps(e)) 68 | return None 69 | 70 | def get_ou_memberships_for(self, dn): 71 | memberships = [] 72 | 73 | ou_common_names = self.settings.get([OU]) 74 | if ou_common_names is None: 75 | return False 76 | 77 | ou_filter = self.settings.get([OU_FILTER]) 78 | ou_member_filter = self.settings.get([OU_MEMBER_FILTER]) 79 | for ou_common_name in str(ou_common_names).split(","): 80 | result = self.search("(&" + 81 | "(" + ou_filter % ou_common_name.strip() + ")" + 82 | "(" + (ou_member_filter % dn) + ")" + 83 | ")") 84 | if result is not None and result[DISTINGUISHED_NAME] is not None: 85 | self.logger.debug("%s is a member of %s" % (dn, result[DISTINGUISHED_NAME])) 86 | memberships.append(ou_common_name) 87 | return memberships 88 | 89 | 90 | class DependentOnLDAPConnection: 91 | # noinspection PyShadowingNames 92 | def __init__(self, ldap): 93 | self._ldap = ldap 94 | 95 | @property 96 | def ldap(self): 97 | return self._ldap 98 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | ######################################################################################################################## 4 | # Do not forget to adjust the following variables to your own plugin. 5 | 6 | # The plugin's identifier, has to be unique 7 | plugin_identifier = "auth_ldap" 8 | 9 | # The plugin's python package, should be "octoprint_", has to be unique 10 | plugin_package = "octoprint_%s" % plugin_identifier 11 | 12 | # The plugin's human readable name. Can be overwritten within OctoPrint's internal data via __plugin_name__ in the 13 | # plugin module 14 | plugin_name = "Auth LDAP" 15 | 16 | # The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module 17 | plugin_version = "1.1.0" 18 | 19 | # The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin 20 | # module 21 | plugin_description = "LDAP Auth provider" 22 | 23 | # The plugin's author. Can be overwritten within OctoPrint's internal data via __plugin_author__ in the plugin module 24 | plugin_author = "Guillaume Gill, Seth Battis, Paul K. Stelis" 25 | 26 | # The plugin's author's mail address. 27 | plugin_author_email = "seth@battis.net" 28 | 29 | # The plugin's homepage URL. Can be overwritten within OctoPrint's internal data via __plugin_url__ in the plugin module 30 | plugin_url = "https://github.com/battis/OctoPrint-LDAP" 31 | 32 | # The plugin's license. Can be overwritten within OctoPrint's internal data via __plugin_license__ in the plugin module 33 | plugin_license = "AGPLv3" 34 | 35 | # Any additional requirements besides OctoPrint should be listed here 36 | plugin_requires = ["python-ldap"] 37 | # TODO figure out how to automate installation of these dependencies? 38 | # To get python-ldap installed, you need its development/build dependencies installed: 39 | # apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev 40 | 41 | ### -------------------------------------------------------------------------------------------------------------------- 42 | ### More advanced options that you usually shouldn't have to touch follow after this point 43 | ### -------------------------------------------------------------------------------------------------------------------- 44 | 45 | # Additional package data to install for this plugin. The subfolders "templates", "static" and "translations" will 46 | # already be installed automatically if they exist. Note that if you add something here you'll also need to update 47 | # MANIFEST.in to match to ensure that python setup.py sdist produces a source distribution that contains all your 48 | # files. This is sadly due to how python's setup.py works, see also http://stackoverflow.com/a/14159430/2028598 49 | plugin_additional_data = [] 50 | 51 | # Any additional python packages you need to install with your plugin that are not contained in .* 52 | plugin_additional_packages = [] 53 | 54 | # Any python packages within .* you do NOT want to install with your plugin 55 | plugin_ignored_packages = [] 56 | 57 | # Additional parameters for the call to setuptools.setup. If your plugin wants to register additional entry points, 58 | # define dependency links or other things like that, this is the place to go. Will be merged recursively with the 59 | # default setup parameters as provided by octoprint_setuptools.create_plugin_setup_parameters using 60 | # octoprint.util.dict_merge. 61 | # 62 | # Example: 63 | # plugin_requires = ["someDependency==dev"] 64 | # additional_setup_parameters = {"dependency_links": ["https://github.com/someUser/someRepo/archive/master.zip#egg=someDependency-dev"]} 65 | additional_setup_parameters = {} 66 | 67 | ######################################################################################################################## 68 | 69 | from setuptools import setup 70 | 71 | try: 72 | import octoprint_setuptools 73 | except: 74 | print("Could not import OctoPrint's setuptools, are you sure you are running that under " 75 | "the same python installation that OctoPrint is installed under?") 76 | import sys 77 | 78 | sys.exit(-1) 79 | 80 | setup_parameters = octoprint_setuptools.create_plugin_setup_parameters( 81 | identifier=plugin_identifier, 82 | package=plugin_package, 83 | name=plugin_name, 84 | version=plugin_version, 85 | description=plugin_description, 86 | author=plugin_author, 87 | mail=plugin_author_email, 88 | url=plugin_url, 89 | license=plugin_license, 90 | requires=plugin_requires, 91 | additional_packages=plugin_additional_packages, 92 | ignored_packages=plugin_ignored_packages, 93 | additional_data=plugin_additional_data 94 | ) 95 | 96 | if len(additional_setup_parameters): 97 | from octoprint.util import dict_merge 98 | 99 | setup_parameters = dict_merge(setup_parameters, additional_setup_parameters) 100 | 101 | setup(**setup_parameters) 102 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/plugin.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | from octoprint.plugin import TemplatePlugin, RestartNeedingPlugin 5 | from octoprint.settings import settings 6 | from octoprint_auth_ldap.constants import DEFAULT_ADMIN_GROUP, DEFAULT_USER_GROUP, OU_FILTER, OU_MEMBER_FILTER, OU, \ 7 | REQUEST_TLS_CERT, SEARCH_BASE, URI 8 | from octoprint_auth_ldap.ldap import LDAPConnection 9 | from octoprint_auth_ldap.tweaks import SettingsPlugin 10 | from octoprint_auth_ldap.user_manager import LDAPUserManager 11 | 12 | 13 | class AuthLDAPPlugin(SettingsPlugin, TemplatePlugin, RestartNeedingPlugin): 14 | # noinspection PyUnusedLocal,PyShadowingNames 15 | def ldap_user_factory(self, components, settings): 16 | self._user_manager = LDAPUserManager(plugin=self, ldap=LDAPConnection(plugin=self)) 17 | return self._user_manager 18 | 19 | # Softwareupdate hook 20 | 21 | def check_config(self): 22 | return dict( 23 | auth_ldap=dict( 24 | displayName=self._plugin_name, 25 | displayVersion=self._plugin_version, 26 | 27 | # version check: github repository 28 | type="github_release", 29 | user="battis", 30 | repo="OctoPrint-LDAP", 31 | current=self._plugin_version, 32 | 33 | # update method: pip 34 | pip="https://github.com/battis/OctoPrint-LDAP/archive/{target_version}.zip" 35 | ) 36 | ) 37 | 38 | # SettingsPlugin 39 | 40 | def get_settings_defaults(self): 41 | return dict( 42 | auth_password=None, 43 | auth_user=None, 44 | default_admin_group=False, 45 | default_user_group=True, 46 | 47 | # TODO expose in settings GUi 48 | ldap_group_key_prefix="ldap_", 49 | ldap_parent_group_description="Generated by %s plugin, with membership synced automatically based on LDAP " 50 | "configuration" % self._plugin_name, 51 | ldap_parent_group_key="ldap", 52 | ldap_parent_group_name="LDAP-Authenticated Users", 53 | 54 | ou_filter="ou=%s", 55 | ou_member_filter="uniqueMember=%s", 56 | ou=None, 57 | local_cache=False, 58 | request_tls_cert=None, 59 | search_base=None, 60 | search_filter="uid=%s", 61 | search_term_transform=None, 62 | uri=None, 63 | userid_field=None, 64 | userid_pattern=None 65 | ) 66 | 67 | def get_settings_restricted_paths(self): 68 | return dict( 69 | admin=self.get_settings_defaults().keys(), 70 | user=[], 71 | never=[] 72 | ) 73 | 74 | def get_settings_version(self): 75 | return 3 76 | 77 | def on_settings_migrate(self, target, current): 78 | if target != current: 79 | self._logger.info( 80 | "Migrating %s settings from version %s to version %s" % (self._plugin_name, current, target)) 81 | if current is None: 82 | self.migrate_settings_1_to_2() 83 | if current != 3: # intentional fall-through to bring None _and_ 2 to 3 (my kingdom for a switch statement!) 84 | self.migrate_settings_2_to_3() 85 | 86 | def migrate_settings_1_to_2(self): 87 | # changing settings location to plugin standard location and renaming to simplify access 88 | self._logger.debug("Attempting to migrate settings from version 1 to version 2") 89 | 90 | # migrate old settings to new locations and erase old settings 91 | prev_settings = dict( # prev_setting_name="new_setting_name" 92 | ldap_uri=URI, 93 | ldap_tls_reqcert=REQUEST_TLS_CERT, 94 | ldap_search_base=SEARCH_BASE, 95 | ldap_groups="groups" 96 | ) 97 | for prev_key, key in prev_settings.items(): 98 | prev_value = settings().get(["accessControl", prev_key]) 99 | if prev_value is not None: 100 | cleaned_prev_value = prev_value 101 | if prev_key == "ldap_tls_reqcert" and prev_value == "demand": 102 | cleaned_prev_value = True 103 | self.settings.set([key], cleaned_prev_value) 104 | self._logger.info( 105 | "accessControl.%s=%s setting migrated to plugins.%s.%s=%s" 106 | % (prev_key, prev_value, self._identifier, key, cleaned_prev_value)) 107 | else: 108 | self._logger.debug('accessControl.%s=None, migration not necessary' % prev_key) 109 | settings().set(["accessControl", prev_key], None) 110 | 111 | def migrate_settings_2_to_3(self): 112 | # renaming to get rid of roles in favor of local groups, and clarifying LDAP group settings 113 | self._logger.debug("Attempting to migrate settings from version 2 to version 3") 114 | 115 | # migrate old settings to new locations and erase old settings 116 | prev_settings = dict( # prev_setting_name="new_setting_name" 117 | default_role_admin=DEFAULT_ADMIN_GROUP, 118 | default_role_user=DEFAULT_USER_GROUP, 119 | group_filter=OU_FILTER, 120 | group_member_filter=OU_MEMBER_FILTER, 121 | groups=OU 122 | ) 123 | for prev_key, key in prev_settings.items(): 124 | prev_value = self.settings.get([prev_key]) 125 | if prev_value is not None: 126 | self.settings.set([key], prev_value) 127 | self._logger.info( 128 | "plugin.%s.%s=%s setting migrated to plugins.%s.%s=%s" 129 | % (self._identifier, prev_key, prev_value, self._identifier, key, prev_value)) 130 | else: 131 | self._logger.debug('plugin.%s.%s=None, migration not necessary' % (self._identifier, prev_key)) 132 | self.settings.set([prev_key], None) 133 | 134 | # TemplatePlugin 135 | 136 | def get_template_configs(self): 137 | return [ 138 | dict(type="settings", custom_bindings=False), # must mark custom_bindings False to load settings in GUI 139 | ] 140 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OctoPrint Auth LDAP Plugin 2 | --- 3 | 4 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/battis/OctoPrint-LDAP/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/battis/OctoPrint-LDAP/?branch=master) 5 | 6 | #### Prerequisites 7 | 8 | Before installing this plugin, consult [the python-ldap documentation for its build prerequisites on your system](https://www.python-ldap.org/en/python-ldap-3.3.0/installing.html#build-prerequisites) or [instructions for installing pre-built binaries on your system](https://www.python-ldap.org/en/python-ldap-3.3.0/installing.html#pre-built-binaries). For example, on Debian-based systems (such as Raspbian) with octoprint version 1.8.6 and above, it is necessary to preinstall a collection of supporting libraries in order for python-ldap to install properly: 9 | 10 | ```bash 11 | apt-get install build-essential python3-dev python2.7-dev libldap2-dev \ 12 | libsasl2-dev slapd ldap-utils python-tox lcov valgrind 13 | ``` 14 | 15 | Minimally, on Raspbian with octoprint version 1.8.6 and above: 16 | 17 | ```bash 18 | apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev 19 | ``` 20 | 21 | If you are using the plugin with an octoprint version before 1.8.6 you also need to install passlib librarie: 22 | 23 | ```bash 24 | apt-get install build-essential python3-dev python2.7-dev libldap2-dev \ 25 | libsasl2-dev slapd ldap-utils python-tox lcov valgrind passlib 26 | ``` 27 | 28 | or for minimal: 29 | 30 | ```bash 31 | apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev passlib 32 | ``` 33 | 34 | If installing on Windows, you will need to find the proper pre-built binary of python-ldap, as directed in the [python-ldap documentation](https://www.python-ldap.org/en/python-ldap-3.3.0/installing.html#pre-built-binaries). 35 | 36 | #### Installation 37 | 38 | You can install this via the OctoPrint plugin manager GUI using this URL: 39 | 40 | ``` 41 | https://github.com/gillg/OctoPrint-LDAP/archive/refs/heads/master.zip 42 | ``` 43 | 44 | The plugin may also be installed within the oprint venv using the command 45 | 46 | ```bash 47 | pip install https://github.com/gillg/OctoPrint-LDAP/archive/refs/heads/master.zip 48 | ``` 49 | 50 | #### General Configuration 51 | 52 | You could configure LDAP server in plugin config, or manually in config.yaml 53 | 54 | ```YAML 55 | plugins: 56 | auth_ldap: 57 | uri: ldaps://example.com 58 | auth_user: example\authuser 59 | auth_password: s00p3rS3KRE7 60 | search_base: dc=example,dc=com 61 | ou: Lab Users, Lab Staff 62 | ``` 63 | 64 | #### Details 65 | 66 | The plugin extends the `FilebasedUserManager` to becomae an `LDAPUserManager` such that when a user logs in: 67 | 68 | 1. The local `users.yaml` user list is consulted first -- and, if the user is present, treated as the authoritative credential record 69 | 2. If the user is not found locally, the LDAP directory is searched for their username and, optionally, their membership ins specific groups is verified. 70 | 3. If the user is found in the LDAP directory, they are optionally cached locally in `users.yaml` as an `LDAPUser` (extending `User`) with configurable default roles in OctoPrint. 71 | 4. An attempt is made to bind the user to the LDAP directory using the provided password, double-checking that the user is still a member of any required groups, if configured. If successful, the user is logged in. 72 | 73 | #### Optional Authenticated Search 74 | 75 | Most LDAP servers require some level of authentication to perform a search of the directory. Credentials with which to search the directory can be provided: 76 | 77 | ```YAML 78 | plugins: 79 | auth_ldap: 80 | auth_user: example\authuser 81 | auth_password: s00p3rS3KRE7 82 | ``` 83 | 84 | Alternatively you can use `auth_password_file` to avoid keeping the password in 85 | your configuration file. Be mindful of line breaks in your password file. An 86 | end-of-line at the end of the file will place a line break in the password 87 | submitted to LDAP. Also ensure the Octoprint user has permission to read the 88 | file. 89 | 90 | ```YAML 91 | plugins: 92 | auth_ldap: 93 | auth_user: example\authuser 94 | auth_password_file: /path/to/password/file 95 | ``` 96 | 97 | If no authentication username is provided, an anonymous search will be performed (which may not generate useful results on most servers). The `auth_user` can be provided as a distinguished name (`uid=authuser,dc=example,dc=com`), principal name (`authuser@example.com`) or UID (`example\authuser`), depending on the needs of the system. 98 | 99 | #### Default Roles/Activity 100 | 101 | By default, all LDAP users are treated as active OctoPrint users. They may be configured to default to being admins as well. If LDAP users are cached locally, individual users may be marked inactive within OctoPrint and denied access. 102 | 103 | #### Local Caching 104 | 105 | By default, LDAP users are not cached locally, to prevent the potentially complex outcomes described below. 106 | 107 | If the LDAP users are cached locally, admin users can manage user permissions and account state within Octoprint. This would allow the default role for LDAP users to be generic OctoPrint users, but for some trusted individuals to have their OctoPrint permissions upgraded to admin locally. Additionally, LDAP users can procure API keys for the system. 108 | 109 | As the plugin's group filter (or the group memberships within the LDAP directory) may change over time, LDAP users' group membership is verified against the configured groups, along with their password, on each login. 110 | 111 | In `users.yaml`, the LDAP users are stored thus: 112 | 113 | ```YAML 114 | example_user: 115 | active: true 116 | apikey: null 117 | dn: cn=Example user,dc=example,dc=com 118 | groups: 119 | - ldap_lab_users 120 | - users 121 | password: null 122 | settings: {} 123 | type: LDAP 124 | ``` 125 | 126 | Note that the password hash is stored as null intentionally, to prevent accidental password matching. The assumption being that, if this plugin is disabled, the LDAP users in `users.yaml` are still parseable by the `FilebasedUserManager` (since doing otherwise causes the system to choke), so lingering cached LDAP users could then be treated as standard local users. Fortunately, as password checking is done by hashing the proffered password and comparing with the stored hash... and nothing hashes to null, it is impossible to provide a password for a cached LDAP user that will provide access. 127 | 128 | #### Search Base Gotcha 129 | 130 | Observationally, I have noticed that the Microsoft LDAP server appears to require the search base to include an organizational unit, as well as the domain controller. (e.g. `OU=All Users,DC=example,DC=com`), while OpenLDAP appears to be less demanding and will simply accept a domain controller as the search base (e.g. `DC=example,DC=com`). 131 | 132 | If your users are partitioned into more than one top-level organizational unit within the Microsoft LDAP server, there is no way to configure a wild-card search base -- the only way forward would likely be to update the plugin source to accept multiple search bases and then search against each base in turn. Or create one super-OU to contain your disparate OUs. 133 | 134 | #### Groups 135 | 136 | In addition to authenticating against the LDAP directory, users may also be filtered for current membership in specific LDAP groups (a.k.a. OUs or Organizational Units). If not specified, no group membership check is performed. Groups are listed as a comma-separated (white space agnostic) list. For example: 137 | 138 | ```YAML 139 | plugins: 140 | auth_ldap: 141 | ou: Lab Users, Lab Staff 142 | ``` 143 | 144 | If local caching is enabled, LDAP OU groups will by synced as OctoPrint groups, to allow for per-group permissions configuration. All synced groups are subgroups of a parent OctoPrint group. By default the parent group is `LDAP-Authorized Users` with key `ldap` and the synced OU-as-groups are named based on the settings configuration (e.g. `Lab Users` OU would become a group named `Lab Users` with key `ldap_lab_users`). 145 | 146 | The naming scheme on these groups can be configured directly through config.yaml with the following keys (and default values): 147 | 148 | ```YAML 149 | plugins: 150 | auth_ldap: 151 | ldap_group_key_prefix: ldap_ 152 | ldap_parent_group_description: Generated by Auth LDAP plugin, with membership synced automatically based on LDAP configuration 153 | ldap_parent_group_key: ldap 154 | ldap_parent_group_name: LDAP-Authenticated Users 155 | ``` 156 | 157 | #### Configurable Search Filters 158 | 159 | As LDAP directory configuration varies, it may be necessary to configure how users are searched for within the directory. 160 | 161 | ##### User Search Filter 162 | 163 | By default, the provided `userid` is searched for using the provided search base and the search filter template `uid=%s`. This may be configured differently on some systems. For example, one alternate search filter template configuration might be: 164 | 165 | ```YAML 166 | plugins: 167 | auth_ldap: 168 | search_filter: userPrincipalName=%s@example.com 169 | ``` 170 | 171 | This would match the provided username as an email address against the `userPrincipalName` field. The `%s` placeholder would be replaced with the provided user id. 172 | 173 | ##### Group Membership 174 | 175 | Membership in LDAP groups is verified by searching for a group with a particular name that has a member with the LDAP distinguished name (DN) that matches the provided user. Two configuration fields affect this matching: 176 | 177 | ```YAML 178 | plugins: 179 | auth_ldap: 180 | ou_filter: cn=%s 181 | ou_member_filter: uniqueMember=%s 182 | ``` 183 | 184 | This configuration would generate a search filter that would test against each provided OU name in turn, using the user's LDAP-provided DN: `"(&(cn=%s)(uniqueMember=%s))" % (ou_name, dn)`, which would end up looking like `(&(cn=Lab Users)(uniqueMember=uid=example_user,dc=example.dc=com))` 185 | 186 | ##### Search Term Transform 187 | 188 | OctoPrint searches for users in a case-sensitve manner by default. However, it becomes a management issue (if local caching is turned on) to have cached each case-sensitive search for the same user (e.g. `testuser`, `TESTUSER`, `TestUser`, `tEsTuSeR`, etc.). In order to manage this issue, the `search_term_transform` setting allows you to specify a string transformation (e.g. `upper` or `lower`) to be applied to search terms if they are not found already cached. 189 | 190 | ```YAML 191 | plugins: 192 | auth_ldap: 193 | search_term_transform: lower 194 | ``` 195 | 196 | The result of this will be that the user ID entered in the login dialog will be transformed using this call: 197 | 198 | ```python 199 | userid = getattr(str, "lower")(str(userid)) 200 | ``` 201 | 202 | Note that this does not provide a capability for more nuanced transformations at this pouint. 203 | 204 | ## Contributors 205 | 206 | Original design and implementation by [Gillaume Gill](https://github.com/gillg/OctoPrint-LDAP). 207 | 208 | Authenticated lookup, configuration and caching by [Seth Battis](https://github.com/battis/OctoPrint-LDAP). 209 | 210 | Initial OctoPrint 1.4 compatibility by [Paul K. Stelis](https://github.com/paulkstelis/OctoPrint-LDAP). 211 | 212 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/templates/auth_ldap_settings.jinja2: -------------------------------------------------------------------------------- 1 |
2 | 3 |

{{ _('Auth LDAP Settings') }}

4 | 5 | 11 | 12 |
13 |
14 | 15 |
16 | 17 | {{ _('Server') }} 18 | 19 | 20 |
21 | 24 | The URI of the LDAP server. Must include the protocol, and may include the port number. (for example ldaps://example.com:1337) 25 |
26 | 27 | 29 |
30 | 32 |
33 |
34 | 35 |
36 | 37 | {{ _('Authenticated Search') }} 38 | 39 |
40 | Most LDAP servers do not allow anonymous searches. The usual configuration is to have a read-only 41 | user that create an authenticated bind to the server in order to search for other users. 42 |
43 | 44 | 46 |
47 | 50 | Entered as a a distinguished name (uid=authuser,dc=example,dc=com), principle name (authuser@example.com), or as a UID (example\authuser) 51 |
52 | 53 | 55 |
56 | 58 | Due to the OctoPrint settings architecture, this password will be stored in `config.yaml` in clear text. 59 |
60 |
61 |
62 | 63 |
64 |
65 | 66 | {{ _('Search Base') }} 67 | 68 |
The search base should identify a point in the hierarchy that includes all users 69 | and groups that will need access to this instance of OctoPrint. 70 |
71 | 72 | 73 |
74 | 76 | If connecting to a Microsoft LDAP server, the search base must include an organizational unit (e.g. ou=All users,dc=example,dc=com), however OpenLDAP will accept a domain controller (e.g. dc=example,dc=com) as the search base. 77 |
78 | 79 | 81 |
82 | 84 | Use %s as placeholder for login user ID. The default filter is 85 | uid=%s, but on Microsoft LDAP userPrincipalName=%s@example.com may 86 | also be appropriate. 87 |
88 |
89 | 90 |
91 | 92 | {{ _('Caching and User Defaults') }} 93 | 94 | 96 |
97 | 99 | A python string transformation (e.g. lower or upper) used to limit 100 | case-sensitivity when searching for users (converting everyone to lowercase avoids 101 | example, EXAMPLE, Example and eXaMpLe all 102 | being different users. 103 |
104 | 105 | 106 |
107 | 109 | By default, LDAP users are not cached locally to avoid complex permissions checks. However, caching users locally does allow for users (and groups) to receive customized permissions on this local OctoPrint instance, either individually or based on their LDAP group membership. 110 |
111 | 112 | 114 |
115 | 117 | LDAP users will automatically become members of the generic OctoPrint Users group. (Uncheck to configure narrower permissions based on LDAP group membership.) 118 |
119 | 120 | 122 |
123 | 125 | LDAP users will automatically be members of the generic OctoPrint Admin group, having full access to all settings. (Uncheck for sanity.) 126 |
127 |
128 |
129 | 130 |
131 |
132 | 133 | {{ _('Filter by LDAP Group') }} 134 | 135 | 136 |
137 | 140 | Common names or other identifying fields for LDAP groups whose members will be allowed to sign in. If this is left blank, all users that can be found on the LDAP server from the search base will be allowed to log in. A comma-delimited list. 141 |
142 | 143 | 144 |
145 | 147 | Use %s as placeholder for group name. A filter to convert the list of common 148 | names into an LDAP search to identify the actual group memberships of users. The default value 149 | is ou=%s 150 |
151 | 152 | 154 |
155 | 157 | Use %s as placeholder for user's distinguished name. A filter to confirm a 158 | user's membership in a group. The default value is uniqueMember=%s 159 |
160 |
161 |
162 |
163 |
164 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/group_manager.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | import io 5 | import os 6 | import re 7 | 8 | import yaml 9 | from octoprint.access.groups import FilebasedGroupManager, Group, GroupAlreadyExists 10 | from octoprint.access.permissions import Permissions, OctoPrintPermission 11 | from octoprint.util import atomic_write 12 | from octoprint_auth_ldap.constants import OU, OU_FILTER, DISTINGUISHED_NAME, LDAP_PARENT_GROUP_NAME, \ 13 | LDAP_PARENT_GROUP_DESCRIPTION, LDAP_PARENT_GROUP_KEY, LDAP_GROUP_KEY_PREFIX 14 | from octoprint_auth_ldap.group import LDAPGroup 15 | from octoprint_auth_ldap.ldap import DependentOnLDAPConnection 16 | from octoprint_auth_ldap.tweaks import DependentOnSettingsPlugin 17 | from octoprint_auth_ldap.user import LDAPUser 18 | 19 | 20 | class LDAPGroupManager(FilebasedGroupManager, DependentOnSettingsPlugin, DependentOnLDAPConnection): 21 | 22 | def __init__(self, plugin, ldap, path=None): 23 | DependentOnSettingsPlugin.__init__(self, plugin) 24 | DependentOnLDAPConnection.__init__(self, ldap) 25 | FilebasedGroupManager.__init__(self, path) 26 | 27 | def add_group( 28 | self, 29 | key, 30 | name, 31 | description, 32 | permissions, 33 | subgroups, 34 | default=False, 35 | removable=True, 36 | changeable=True, 37 | toggleable=True, 38 | overwrite=False, 39 | notify=True, 40 | save=True, 41 | dn=None 42 | ): 43 | if dn is None: 44 | FilebasedGroupManager.add_group( 45 | self, 46 | key=key, 47 | name=name, 48 | description=description, 49 | permissions=permissions, 50 | subgroups=subgroups, 51 | default=default, 52 | removable=False if key == LDAP_PARENT_GROUP_KEY else removable, 53 | changeable=True if key == LDAP_PARENT_GROUP_KEY else changeable, 54 | toggleable=toggleable, 55 | overwrite=overwrite, 56 | notify=notify, 57 | save=save 58 | ) 59 | else: 60 | if key in self._groups and not overwrite: 61 | raise GroupAlreadyExists(key) 62 | 63 | if not permissions: 64 | permissions = [] 65 | 66 | permissions = self._to_permissions(*permissions) 67 | assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) 68 | 69 | subgroups = self._to_groups(*subgroups) 70 | assert (all(map(lambda g: isinstance(g, Group), subgroups))) 71 | 72 | group = LDAPGroup( 73 | key=key, 74 | name=name, 75 | description=description, 76 | permissions=permissions, 77 | subgroups=subgroups, 78 | default=default, 79 | changeable=True, 80 | removable=False, 81 | dn=dn 82 | ) 83 | self._groups[key] = group 84 | self.logger.debug("Added group %s as %s" % (name, LDAPGroup.__name__)) 85 | 86 | if save: 87 | self._dirty = True 88 | self._save() 89 | 90 | if notify: 91 | self._notify_listeners("added", group) 92 | 93 | def _to_group_key(self, ou_common_name): 94 | return "%s%s" % ( 95 | self.settings.get([LDAP_GROUP_KEY_PREFIX]), re.sub(r"\W+", "_", ou_common_name.strip().lower())) 96 | 97 | def _refresh_ldap_groups(self): 98 | ou = self.settings.get([OU]) 99 | if ou is not None or ou == "": # FIXME allowing empty string settings is dumb 100 | self.logger.info("Syncing LDAP groups to local groups based on %s settings" % self.plugin.identifier) 101 | 102 | try: 103 | self.add_group(key=self.settings.get([LDAP_PARENT_GROUP_KEY]), 104 | name=self.settings.get([LDAP_PARENT_GROUP_NAME]), 105 | description=self.settings.get([LDAP_PARENT_GROUP_DESCRIPTION]), 106 | permissions=[], 107 | subgroups=[], 108 | overwrite=False 109 | ) 110 | except GroupAlreadyExists: 111 | assert True 112 | 113 | organizational_units = [group.strip() for group in str(self.settings.get([OU])).split(",")] 114 | ldap_groups = [group.get_name() for group in self._groups.values() if isinstance(group, LDAPGroup)] 115 | ou_filter = self.settings.get([OU_FILTER]) 116 | 117 | for ou_common_name in list(set(organizational_units) - set(ldap_groups)): 118 | key = self._to_group_key(ou_common_name) 119 | this_group = self.find_group(key) 120 | if this_group is None: 121 | result = self.ldap.search("(" + ou_filter % ou_common_name.strip() + ")") 122 | self.add_group(key=key, 123 | name=ou_common_name, 124 | dn=result[DISTINGUISHED_NAME], 125 | description="Synced LDAP Group", 126 | permissions=[], 127 | subgroups=[], 128 | toggleable=True, 129 | removable=False, 130 | changeable=True, 131 | save=False 132 | ) 133 | 134 | self.update_group( 135 | self.settings.get([LDAP_PARENT_GROUP_KEY]), 136 | subgroups=[group for group in self._groups.values() if isinstance(group, LDAPGroup)], 137 | save=True 138 | ) 139 | 140 | def get_ldap_groups_for(self, dn): 141 | if isinstance(dn, LDAPUser): 142 | dn = dn.distinguished_name 143 | self._refresh_ldap_groups() 144 | memberships = self.ldap.get_ou_memberships_for(dn) 145 | if memberships is False: 146 | return [] 147 | return list(map(lambda g: self._to_group_key(g), memberships)) 148 | 149 | def _load(self): 150 | if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): 151 | try: 152 | with io.open(self._groupfile, 'rt', encoding='utf-8') as f: 153 | data = yaml.safe_load(f) 154 | version = data.pop("_version", 1) 155 | 156 | if "groups" not in data: 157 | groups = data 158 | data = dict(groups=groups) 159 | 160 | groups = data.get("groups", dict()) 161 | tracked_permissions = data.get("tracked", list()) 162 | 163 | for key, attributes in groups.items(): 164 | if key in self._groups: 165 | # group is already there (from the defaults most likely) 166 | if not self._groups[key].is_changeable(): 167 | # group may not be changed -> bail 168 | continue 169 | 170 | removable = self._groups[key].is_removable() 171 | changeable = self._groups[key].is_changeable() 172 | toggleable = self._groups[key].is_toggleable() 173 | else: 174 | removable = True 175 | changeable = True 176 | toggleable = True 177 | 178 | permissions = self._to_permissions(*attributes.get("permissions", [])) 179 | default_permissions = self.default_permissions_for_group(key) 180 | for permission in default_permissions: 181 | if permission.key not in tracked_permissions and permission not in permissions: 182 | permissions.append(permission) 183 | 184 | subgroups = attributes.get("subgroups", []) 185 | 186 | group_type = attributes.get("type", False) 187 | 188 | if group_type == LDAPGroup.GROUP_TYPE: 189 | self.logger.debug("Loading group %s as %s" % (attributes.get("name", key), LDAPGroup.__name__)) 190 | group = LDAPGroup( 191 | key, 192 | attributes.get("name", key), 193 | description=attributes.get("description", ""), 194 | permissions=permissions, 195 | subgroups=subgroups, 196 | default=attributes.get("default", False), 197 | removable=False, 198 | changeable=changeable, 199 | toggleable=toggleable, 200 | dn=attributes.get(DISTINGUISHED_NAME, None) 201 | ) 202 | else: 203 | self.logger.debug("Loading group %s as %s" % (attributes.get("name", key), Group.__name__)) 204 | group = Group(key, attributes.get("name", ""), 205 | description=attributes.get("description", ""), 206 | permissions=permissions, 207 | subgroups=subgroups, 208 | default=attributes.get("default", False), 209 | removable=removable, 210 | changeable=changeable, 211 | toggleable=toggleable) 212 | self._groups[key] = group 213 | 214 | for group in self._groups.values(): 215 | group._subgroups = self._to_groups(*group._subgroups) 216 | 217 | except Exception: 218 | self.logger.exception("Error while loading groups from file {}".format(self._groupfile)) 219 | 220 | def _save(self, force=False): 221 | if self._groupfile is None or not self._dirty and not force: 222 | return 223 | 224 | groups = dict() 225 | for key, group in self._groups.items(): 226 | if not group or not isinstance(group, Group): 227 | self.logger.debug('Not saving %s' % key) 228 | continue 229 | 230 | if isinstance(group, LDAPGroup): 231 | self.logger.debug("Saving group %s as %s" % (group.get_name(), LDAPGroup.__name__)) 232 | groups[key] = dict( 233 | type=LDAPGroup.GROUP_TYPE, 234 | dn=group.distinguished_name, 235 | 236 | name=group.get_name(), 237 | description=group.get_description(), 238 | permissions=self._from_permissions(*group.permissions), 239 | subgroups=self._from_groups(*group.subgroups), 240 | default=group.is_default() 241 | ) 242 | else: 243 | self.logger.debug("Saving group %s as %s" % (group.get_name(), Group.__name__)) 244 | groups[key] = dict( 245 | name=group._name, 246 | description=group._description, 247 | permissions=self._from_permissions(*group._permissions), 248 | subgroups=self._from_groups(*group._subgroups), 249 | default=group._default 250 | ) 251 | 252 | data = dict(groups=groups, 253 | tracked=[x.key for x in Permissions.all()]) 254 | 255 | with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: 256 | import yaml 257 | yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) 258 | self._dirty = False 259 | self._load() 260 | -------------------------------------------------------------------------------- /octoprint_auth_ldap/user_manager.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | import io 5 | import os 6 | 7 | import yaml 8 | from passlib import pwd 9 | from ldap.filter import filter_format 10 | from octoprint.access.users import FilebasedUserManager, User, UserAlreadyExists 11 | from octoprint.util import atomic_write 12 | from octoprint_auth_ldap.constants import LOCAL_CACHE, SEARCH_FILTER, SEARCH_TERM_TRANSFORM, DISTINGUISHED_NAME, OU 13 | from octoprint_auth_ldap.group import LDAPGroup 14 | from octoprint_auth_ldap.group_manager import LDAPGroupManager 15 | from octoprint_auth_ldap.ldap import DependentOnLDAPConnection 16 | from octoprint_auth_ldap.tweaks import DependentOnSettingsPlugin 17 | from octoprint_auth_ldap.user import LDAPUser 18 | 19 | 20 | class LDAPUserManager(FilebasedUserManager, DependentOnSettingsPlugin, DependentOnLDAPConnection): 21 | 22 | def __init__(self, plugin, ldap, **kwargs): 23 | DependentOnSettingsPlugin.__init__(self, plugin) 24 | DependentOnLDAPConnection.__init__(self, ldap) 25 | FilebasedUserManager.__init__(self, group_manager=LDAPGroupManager(plugin=plugin, ldap=ldap), **kwargs) 26 | 27 | @property 28 | def group_manager(self): 29 | return self._group_manager 30 | 31 | def find_user(self, userid=None, apikey=None, session=None, fresh=False): 32 | self.logger.debug("Search for userid=%s, apiKey=%s, session=%s" % (userid, apikey, session)) 33 | user = FilebasedUserManager.find_user(self, userid=userid, apikey=apikey, session=session) 34 | user, userid = self._find_user_with_transformation(apikey, session, user, userid) 35 | if not user and userid: 36 | user = self._find_user_via_ldap(user, userid) 37 | return user 38 | 39 | def _find_user_via_ldap(self, user, userid): 40 | self.logger.debug("User %s not found locally, treating as LDAP" % userid) 41 | search_filter = self.settings.get([SEARCH_FILTER]) 42 | self.group_manager._refresh_ldap_groups() 43 | """ 44 | operating on the wildly unsafe assumption that the admin who configures this plugin will have their head 45 | screwed on right and we are NOT escaping their search strings... only escaping unsafe user-entered text that 46 | is passed directly to search filters 47 | """ 48 | ldap_user = self.ldap.search(filter_format(search_filter, (userid,))) 49 | if ldap_user is not None: 50 | self.logger.debug("User %s found as dn=%s" % (userid, ldap_user[DISTINGUISHED_NAME])) 51 | groups = self._group_manager.get_ldap_groups_for(ldap_user[DISTINGUISHED_NAME]) 52 | if isinstance(groups, list): 53 | self.logger.debug("Creating new LDAPUser %s" % userid) 54 | if self.settings.get([LOCAL_CACHE]): 55 | self.add_user( 56 | username=userid, 57 | dn=ldap_user[DISTINGUISHED_NAME], 58 | groups=groups, 59 | active=True 60 | ) 61 | user = self._users[userid] 62 | else: 63 | user = LDAPUser( 64 | username=userid, 65 | dn=ldap_user[DISTINGUISHED_NAME], 66 | groups=groups, 67 | active=True 68 | ) 69 | return user 70 | 71 | def _find_user_with_transformation(self, apikey, session, user, userid): 72 | transformation = self.settings.get([SEARCH_TERM_TRANSFORM]) 73 | if not user and userid and transformation: 74 | self.logger.debug("Transforming %s using %s" % (userid, transformation)) 75 | transformed = getattr(str, transformation)(str(userid)) 76 | self.logger.debug("Search for user userid=%s" % transformed) 77 | if transformed != userid: 78 | userid = transformed 79 | user = FilebasedUserManager.find_user(self, userid=userid, apikey=apikey, session=session) 80 | return user, userid 81 | 82 | def add_user(self, 83 | username, 84 | password=pwd.genword(entropy=52, length=20), 85 | active=False, 86 | permissions=None, 87 | groups=None, 88 | apikey=None, 89 | overwrite=False, 90 | dn=None): 91 | if dn is None: 92 | FilebasedUserManager.add_user( 93 | self, 94 | username=username, 95 | password=password, 96 | active=active, 97 | permissions=permissions, 98 | groups=groups, 99 | apikey=apikey, 100 | overwrite=overwrite 101 | ) 102 | else: 103 | if username in self._users.keys() and not overwrite: 104 | raise UserAlreadyExists(username) 105 | 106 | if not permissions: 107 | permissions = [] 108 | permissions = self._to_permissions(*permissions) 109 | 110 | if not groups: 111 | groups = self._group_manager.default_groups 112 | groups = self._to_groups(*groups) 113 | 114 | self._users[username] = LDAPUser( 115 | username=username, 116 | passwordHash=LDAPUserManager.create_password_hash(password, settings=self._settings), 117 | active=active, 118 | permissions=permissions, 119 | groups=groups, 120 | dn=dn, 121 | apikey=apikey 122 | ) 123 | self._dirty = True 124 | self._save() 125 | 126 | def check_password(self, username, password): 127 | user = self.find_user(userid=username) 128 | if isinstance(user, LDAPUser): 129 | # in case group settings changed either in auth_ldap settings OR on LDAP directory 130 | if user.is_active and ( 131 | self.settings.get([OU]) is None or 132 | len(self.refresh_ldap_group_memberships_for(user)) > 0 133 | ): 134 | self.logger.debug("Checking %s password via LDAP" % user.get_id()) 135 | client = self.ldap.get_client(user.distinguished_name, password) 136 | authenticated = client is not None 137 | self.logger.debug("%s was %sauthenticated" % (user.get_name(), "" if authenticated else "not ")) 138 | if authenticated: 139 | user._passwordHash = LDAPUserManager.create_password_hash(password, settings=self._settings) 140 | self._save(force=True) 141 | return authenticated 142 | else: 143 | self.logger.debug("%s is inactive or no longer a member of required groups" % user.get_id()) 144 | else: 145 | self.logger.debug("Checking %s password via users.yaml" % user.get_name()) 146 | return FilebasedUserManager.check_password(self, user.get_name(), password) 147 | return False 148 | 149 | def refresh_ldap_group_memberships_for(self, user): 150 | current_groups = self.group_manager.get_ldap_groups_for(user) 151 | cached_groups = list(filter(lambda g: isinstance(g, LDAPGroup), user.groups)) 152 | self.remove_groups_from_user(user.get_id(), list(set(cached_groups) - set(current_groups))) 153 | self.add_groups_to_user(user.get_id(), list(set(current_groups) - set(cached_groups))) 154 | self.logger.debug("%s is currently a member of %s" % (user.get_id(), current_groups)) 155 | return current_groups 156 | 157 | def refresh_ldap_group_memberships(self): 158 | for user in filter(lambda u: isinstance(u, LDAPUser), self.get_all_users()): 159 | self.refresh_ldap_group_memberships_for(user) 160 | 161 | def _load(self): 162 | if os.path.exists(self._userfile) and os.path.isfile(self._userfile): 163 | self._customized = True 164 | with io.open(self._userfile, 'rt', encoding='utf-8') as f: 165 | data = yaml.safe_load(f) 166 | version = data.pop("_version", 1) 167 | 168 | for name, attributes in data.items(): 169 | permissions = self._to_permissions(*attributes.get("permissions", [])) 170 | groups = attributes.get("groups", { 171 | self._group_manager.user_group # the user group is mandatory for all logged in users 172 | }) 173 | user_type = attributes.get("type", False) 174 | 175 | # migrate from roles to permissions 176 | if "roles" in attributes and "permissions" not in attributes: 177 | self.logger.info("Migrating user %s to new granular permission system" % name) 178 | groups |= set(self._migrate_roles_to_groups(attributes["roles"])) 179 | self._dirty = True 180 | 181 | # because this plugin used to use the groups field, need to wait to make sure it's safe to do this 182 | groups = self._to_groups(*groups) 183 | 184 | apikey = attributes.get("apikey") 185 | user_settings = attributes.get("settings", dict()) 186 | 187 | if user_type == LDAPUser.USER_TYPE: 188 | self.logger.debug("Loading %s as %s" % (name, LDAPUser.__name__)) 189 | self._users[name] = LDAPUser( 190 | username=name, 191 | passwordHash=attributes["password"], 192 | active=attributes["active"], 193 | permissions=permissions, 194 | groups=groups, 195 | dn=attributes[DISTINGUISHED_NAME], 196 | apikey=apikey, 197 | settings=user_settings 198 | ) 199 | else: 200 | self.logger.debug("Loading %s as %s" % (name, User.__name__)) 201 | self._users[name] = User( 202 | username=name, 203 | passwordHash=attributes["password"], 204 | active=attributes["active"], 205 | permissions=permissions, 206 | groups=groups, 207 | apikey=apikey, 208 | settings=user_settings 209 | ) 210 | for session_id in self._sessionids_by_userid.get(name, set()): 211 | if session_id in self._session_users_by_session: 212 | self._session_users_by_session[session_id].update_user(self._users[name]) 213 | 214 | if self._dirty: 215 | self._save() 216 | 217 | else: 218 | self._customized = False 219 | 220 | def _save(self, force=False): 221 | if not self._dirty and not force: 222 | return 223 | 224 | data = {} 225 | for name, user in self._users.items(): 226 | if not user or not isinstance(user, User): 227 | self.logger.debug('Not saving %s' % name) 228 | continue 229 | 230 | if isinstance(user, LDAPUser): 231 | self.logger.debug('Saving %s as %s' % (name, LDAPUser.__name__)) 232 | data[name] = { 233 | "type": LDAPUser.USER_TYPE, 234 | DISTINGUISHED_NAME: user.distinguished_name, 235 | 236 | # password field has to exist because of how FilebasedUserManager processes 237 | # data, but an empty password hash cannot match any entered password (as 238 | # whatever the user enters will be hashed... even an empty password. 239 | "password": user._passwordHash, 240 | 241 | "active": user._active, 242 | "groups": self._from_groups(*user._groups), 243 | "permissions": self._from_permissions(*user._permissions), 244 | "apikey": user._apikey, 245 | "settings": user._settings, 246 | 247 | # TODO: deprecated, remove in 1.5.0 248 | "roles": user._roles 249 | } 250 | else: 251 | self.logger.debug('Saving %s as %s...' % (name, User.__name__)) 252 | data[name] = { 253 | "password": user._passwordHash, 254 | "active": user._active, 255 | "groups": self._from_groups(*user._groups), 256 | "permissions": self._from_permissions(*user._permissions), 257 | "apikey": user._apikey, 258 | "settings": user._settings, 259 | 260 | # TODO: deprecated, remove in 1.5.0 261 | "roles": user._roles 262 | } 263 | 264 | with atomic_write(self._userfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: 265 | yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) 266 | self._dirty = False 267 | self._load() 268 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------