def netactivity(online): global netstate env = Environment.getInstance() if online: netstate = True env.active = True else: env = Environment.getInstance() netstate = False # Function to shut down the client. Do some clean up and close sockets. try: mqtt = PluginRegistry.getInstance("MQTTClientHandler") # Tell others that we're away now e = EventMaker() goodbye = e.Event(e.ClientLeave(e.Id(env.uuid))) if mqtt: mqtt.send_event(goodbye, qos=1) except ValueError: pass finally: env.reset_requested = True env.active = False
def netactivity(online): global netstate env = Environment.getInstance() if online: netstate = True env.active = True else: env = Environment.getInstance() netstate = False # # Function to shut down the client. Do some clean up and close sockets. # mqtt = PluginRegistry.getInstance("MQTTRelayService") # # # Tell others that we're away now # e = EventMaker() # goodbye = e.Event(e.BusClientState( # e.Id(env.uuid), # e.Type('proxy'), # e.State('leave') # )) # if mqtt: # mqtt.backend_mqtt.send_event(goodbye, qos=2) # mqtt.close() env.reset_requested = True env.active = False
def __init__(self): env = Environment.getInstance() self.log = logging.getLogger(__name__) self.log.debug("initializing MQTT service provider") self.env = env self.__cr = None e = EventMaker() self.goodbye = e.Event(e.ClientLeave( e.Id(Environment.getInstance().uuid) ))
def __init__(self, path, name): self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.__base = path self.__path = os.path.join(path, self._prefix, name) self.__name = name self.load()
def process(self, obj, key, valDict): """ Detects whether this password hash was marked as locked or not """ ssl = Environment.getInstance().config.get('http.ssl', default=None) valDict[key]['value'] = [ssl and ssl.lower() in ["true", "yes", "on"]] return key, valDict
def main(): usage = """ Userspace tftp supplicant: create pxelinux configuration files based on external state information. """ Environment.config="fts.conf" Environment.noargs=True env = Environment.getInstance() cfg_path = env.config.get('pxelinux_cfg-path', default = os.sep.join((os.getcwd(), 'pxelinux.cfg'))) static_path = env.config.get('pxelinux_static-path', default = os.sep.join((os.getcwd(), 'pxelinux.static'))) if not os.access(cfg_path, os.F_OK): self.env.log.error("The pxelinux_cfg-path {path} does not exist!".format(path=cfg_path)) if not os.access(static_path, os.F_OK): self.env.log.error("The pxelinux_static-path {path} does not exist!".format(path=static_path)) # TODO: Use reliable method to start and control daemon process debug = "-d" p = subprocess.Popen( "{path}/fts-fuse.py -f {debug} {cfg_path}".format(path=os.getcwd(), debug=debug, cfg_path=cfg_path), shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE ) result = os.waitpid(p.pid, 0) sys.exit(result)
def test_check_auth(): ldap_url = Environment.getInstance().config.get("ldap.url") retry_max = 3 retry_delay = 5 tls = "False" with mock.patch("gosa.backend.utils.ldap.Environment.getInstance") as m_env, \ mock.patch("gosa.backend.utils.ldap.ldap.ldapobject.ReconnectLDAPObject") as m_conn: # ldap.url, bind-user, bind-dn, bind-secret, retry-max, retry-delay, tls m_env.return_value.config.get.side_effect = [ldap_url, 'admin', None, 'secret', retry_max, retry_delay, tls] m_conn.return_value.search_s.return_value = [('fake-dn',)] assert check_auth("admin", "tester") is True assert m_conn.return_value.sasl_interactive_bind_s.called m_env.return_value.config.get.side_effect = [ldap_url, None, "bind-dn", 'secret', retry_max, retry_delay, tls] m_conn.return_value.search_s.return_value = [('fake-dn',), ('2nd-dn',)] assert check_auth("admin", "tester") is False m_conn.return_value.simple_bind_s.assert_called_with("bind-dn", "secret") m_env.return_value.config.get.side_effect = [ldap_url, None, None, None, retry_max, retry_delay, tls] m_conn.return_value.search_s.return_value = [] assert check_auth("admin", "tester") is False m_conn.return_value.simple_bind_s.assert_called_with() m_env.return_value.config.get.side_effect = [ldap_url, None, None, None, retry_max, retry_delay, tls] m_conn.return_value.search_s.side_effect = ldap.INVALID_CREDENTIALS("test error") assert check_auth("admin", "tester") is False m_conn.return_value.simple_bind_s.assert_called_with()
def __init__(self): self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.subtopic = "%s/proxy" % self.env.domain self.mqtt = MQTTHandler(host=self.env.config.get("mqtt.host"), port=self.env.config.getint("mqtt.port", default=1883))
def lockAccountPassword(self, user, object_dn): """ Locks the account password for the given DN """ # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "userPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "w")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) # Get the object for the given dn user = ObjectProxy(object_dn) # Check if there is a userPasswort available and set if not "userPassword" in user.get_attributes(): raise PasswordException(C.make_error("PASSWORD_NO_ATTRIBUTE")) if not user.userPassword: raise PasswordException(C.make_error("PASSWORD_NOT_AVAILABLE")) # Try to detect the responsible password method-class pwd_o = self.detect_method_by_hash(user.userPassword) if not pwd_o: raise PasswordException(C.make_error("PASSWORD_METHOD_UNKNOWN")) # Lock the hash and save it user.userPassword = pwd_o.lock_account(user.userPassword) user.commit()
def setPasswordRecoveryAnswers(self, user, object_dn, data): """ Set the password recovery answers for a user """ data = loads(data) # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "passwordRecoveryHash") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "w")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) user = ObjectProxy(object_dn) method = user.passwordMethod # Try to detect the responsible password method-class pwd_o = self.get_method_by_method_type(method) if not pwd_o: raise PasswordException(C.make_error("PASSWORD_UNKNOWN_HASH", type=method)) # hash the new answers for idx, answer in data.items(): data[idx] = pwd_o.generate_password_hash(self.clean_string(answer), method) print("%s encrypted with %s as index %s => %s" % (self.clean_string(answer), method, idx, data[idx])) # Set the password and commit the changes user.passwordRecoveryHash = dumps(data) user.commit()
def setUserPassword(self, user, object_dn, password): """ Set a new password for a user """ # Do we have write permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "userPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "w")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) user = ObjectProxy(object_dn) method = user.passwordMethod # Try to detect the responsible password method-class pwd_o = self.get_method_by_method_type(method) if not pwd_o: raise PasswordException(C.make_error("PASSWORD_UNKNOWN_HASH", type=method)) # Generate the new password hash using the detected method pwd_str = pwd_o.generate_password_hash(password, method) # Set the password and commit the changes user.userPassword = pwd_str user.commit()
def accountUnlockable(self, user, object_dn): index = PluginRegistry.getInstance("ObjectIndex") # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "isLocked") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "r", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to read %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "r")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) res = index.search({'dn': object_dn, 'userPassword': '******'}, {'userPassword': 1}) if len(res): hsh = res[0]['userPassword'][0] else: # No password hash -> cannot lock/unlock account return False # Try to detect the responsible password method-class pwd_o = self.detect_method_by_hash(hsh) if not pwd_o: # Could not identify password method return False return pwd_o.isUnlockable(hsh)
def available(): # This should always work try: env = Environment.getInstance() return env.config.get("core.otp") is not None except: return False
def __init__(self): env = Environment.getInstance() self.env = env self.log = logging.getLogger(__name__) # Read config values self.__puppet_user = env.config.get("puppet.user", default=env.config.get("client.user", default="gosa")) self.__target_dir = env.config.get("puppet.target", default="/etc/puppet") self.__puppet_command = env.config.get("puppet.command", default="/usr/bin/puppet") self.__report_dir = env.config.get("puppet.report-dir", default="/var/log/puppet") self.__base_dir = getpwnam(self.__puppet_user).pw_dir # Initialize if not already done if not self.puppetIsInitialized(): self.puppetInitialize(True) # Start log listener wm = pyinotify.WatchManager() # pylint: disable-msg=E1101 wm.add_watch(self.__report_dir, pyinotify.IN_CREATE, rec=True, auto_add=True) notifier = pyinotify.ThreadedNotifier(wm, PuppetLogWatcher()) env.threads.append(notifier) notifier.start()
def __init__(self): env = Environment.getInstance() self.env = env self.log = logging.getLogger(__name__) # Create icon cache directory self.spool = self.env.config.get("client.spool", default="/var/spool/gosa")
def __init__(self): super(MQTTClientHandler, self).__init__() e = EventMaker() self.goodbye = e.Event(e.ClientLeave( e.Id(Environment.getInstance().uuid) )) self.will_set("%s/client/%s" % (self.domain, self.env.uuid), self.goodbye, qos=1)
def __init__(self): self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.ppd_dir = self.env.config.get("cups.spool", default="/tmp/spool") if not path.exists(self.ppd_dir): makedirs(self.ppd_dir) self.base_url = "%s/ppd-proxy/" % get_server_url()
def __init__(self): conn = get_system_bus() dbus.service.Object.__init__(self, conn, '/com/gonicus/gosa/puppet') self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.logdir = self.env.config.get("puppet.report-dir", "/var/log/puppet") # Check puppet configuration config = ConfigParser.ConfigParser() config.read('/etc/puppet/puppet.conf') try: if config.get("main", "report", "false") != "true": raise OptionMissing("puppet has no reporting enabled") if config.get("main", "reportdir", "") != self.logdir: raise OptionMissing("reportdir configured in /etc/puppet/puppet.conf and %s do not match" % self.env.config.get('core.config')) if config.get("main", "reports", "") != "store_gosa": raise OptionMissing("storage module probably not compatible") except OptionMissing: self.hint("configuration section for puppet is incomplete") except ConfigParser.NoOptionError: self.hint("configuration section for puppet is incomplete")
def __init__(self): env = Environment.getInstance() self.log = logging.getLogger(__name__) self.log.debug("initializing AMQP service provider") self.env = env self.__cr = None self.__cmdWorker = None
def setUp(self): super(DBusShellHandlerTestCase, self).setUp() self.env = Environment.getInstance() self.path = self.env.config.get("dbus.script-path") if not os.path.exists(self.path): os.makedirs(self.path) with mock.patch("gosa.dbus.plugins.shell.main.dbus.Interface") as m_if: self.handler = DBusShellHandler() self.m_systemd = m_if.return_value # add test script to path for root, dirs, files in os.walk( os.path.join(os.path.dirname(__file__), "shelld")): for script in files: shutil.copyfile(os.path.join(root, script), os.path.join(self.path, script)) if script != "noexec.sh": shutil.copymode(os.path.join(root, script), os.path.join(self.path, script)) if not os.path.exists( os.path.join(os.path.dirname(__file__), "shelld", "test_dir")): os.makedirs( os.path.join(os.path.dirname(__file__), "shelld", "test_dir")) time.sleep(0.2)
def __init__(self, host, port=1883, keepalive=60): self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.connected = False self.client = BaseClient() self.host = host self.port = port self.keepalive = keepalive # set the callbacks self.client.on_connect = self.__on_connect self.client.on_message = self.__on_message self.client.on_subscribe = self.__on_subscribe self.client.on_unsubscribe = self.__on_unsubscribe self.client.on_publish = self.__on_publish self.client.on_log = self.__on_log ssl = self.env.config.getboolean('mqtt.ssl') if ssl is False: ssl = self.env.config.getboolean('http.ssl') if ssl is True: cert = self.env.config.get('mqtt.ca_file', default=None) if cert is not None: self.client.tls_set(cert) self.client.tls_insecure_set( self.env.config.getboolean('mqtt.insecure')) self.subscriptions = {}
def use_test_config(request): env = Environment.getInstance() if has_dbus: # Enable DBus runner dr = DBusRunner() dr.start() PluginRegistry(component='gosa.client.module') # @UnusedVariable env.active = True def shutdown(): env.active = False # Wait for threads to shut down for t in env.threads: if hasattr(t, 'stop'): t.stop() if hasattr(t, 'cancel'): t.cancel() t.join(2) PluginRegistry.shutdown() if has_dbus: dr.stop() request.addfinalizer(shutdown)
def setSambaPassword(self, user, object_dn, password): """ Set a new samba-password for a user """ # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "sambaNTPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "w")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "sambaLMPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % ( user, "isLocked", object_dn, topic, "w")) raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) # Set the password and commit the changes user = ObjectProxy(object_dn) user.sambaNTPassword = nthash.encrypt(password) user.sambaLMPassword = lmhash.encrypt(password) user.commit()
def __init__(self): self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.uuid = dmi_system("uuid") self.mac = self.get_mac_address() self.get_service() self.domain = socket.getfqdn().split('.', 1)[1]
def main(): """ Main programm which is called when the GOsa backend process gets started. It does the main forking os related tasks. """ # Set process list title os.putenv('SPT_NOENV', 'non_empty_value') setproctitle("gosa") # Initialize core environment env = Environment.getInstance() # create temporal credentials for mqtt env.core_uuid = str(uuid4()) env.core_key = str(uuid4()) if not env.base: env.log.critical("GOsa backend needs a 'core.base' do operate on") exit(1) env.log.info("GOsa %s is starting up" % VERSION) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) mainLoop(env)
def setUp(self): """ Stuff to be run before every test """ Environment.config = "sample_test.conf" Environment.noargs = True self.env = Environment.getInstance() self.plugin = SampleModule()
def main(): """ Main programm which is called when the GOsa backend process gets started. It does the main forking os related tasks. """ # Enable DBus runner dr = DBusRunner() dr.start() # Set process list title os.putenv('SPT_NOENV', 'non_empty_value') setproctitle("gosa-session") description = 'Helper commands to notify the GOsa backend about active user sessions on the client.' parser = argparse.ArgumentParser(description=description) parser.add_argument( '-m', '--mode', dest="mode", type=str, help='"start" or "end" to specify the user session state') parser.add_argument('-u', '--user', dest="user", type=str, help='user name') options, unknown = parser.parse_known_args() # Initialize core environment env = Environment.getInstance() notify_backend(env, options.mode, options.user)
def process(self, obj, key, valDict): """ Detects whether this password hash was marked as locked or not """ ssl = Environment.getInstance().config.getboolean('http.ssl') valDict[key]['value'] = [ssl] return key, valDict
def lockAccountPassword(self, user, object_dn): """ Locks the account password for the given DN """ # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "userPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug( "user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % (user, "isLocked", object_dn, topic, "w")) raise ACLException( C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) # Get the object for the given dn user = ObjectProxy(object_dn) # Check if there is a userPasswort available and set if not "userPassword" in user.get_attributes(): raise PasswordException(C.make_error("PASSWORD_NO_ATTRIBUTE")) if not user.userPassword: raise PasswordException(C.make_error("PASSWORD_NOT_AVAILABLE")) # Try to detect the responsible password method-class pwd_o = self.detect_method_by_hash(user.userPassword) if not pwd_o: raise PasswordException(C.make_error("PASSWORD_METHOD_UNKNOWN")) # Lock the hash and save it user.userPassword = pwd_o.lock_account(user.userPassword) user.commit()
def setUserPassword(self, user, object_dn, password): """ Set a new password for a user """ # Do we have write permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "userPassword") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "w", base=object_dn): self.__log.debug( "user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % (user, "isLocked", object_dn, topic, "w")) raise ACLException( C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) user = ObjectProxy(object_dn) method = user.passwordMethod # Try to detect the responsible password method-class pwd_o = self.get_method_by_method_type(method) if not pwd_o: raise PasswordException( C.make_error("PASSWORD_UNKNOWN_HASH", type=method)) # Generate the new password hash using the detected method pwd_str = pwd_o.generate_password_hash(password, method) # Set the password and commit the changes user.userPassword = pwd_str user.commit()
def accountUnlockable(self, user, object_dn): index = PluginRegistry.getInstance("ObjectIndex") # Do we have read permissions for the requested attribute env = Environment.getInstance() topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "isLocked") aclresolver = PluginRegistry.getInstance("ACLResolver") if not aclresolver.check(user, topic, "r", base=object_dn): self.__log.debug( "user '%s' has insufficient permissions to read %s on %s, required is %s:%s" % (user, "isLocked", object_dn, topic, "r")) raise ACLException( C.make_error('PERMISSION_ACCESS', topic, target=object_dn)) res = index.search({ 'dn': object_dn, 'userPassword': '******' }, {'userPassword': 1}) if len(res): hsh = res[0]['userPassword'][0] else: # No password hash -> cannot lock/unlock account return False # Try to detect the responsible password method-class pwd_o = self.detect_method_by_hash(hsh) if not pwd_o: # Could not identify password method return False return pwd_o.isUnlockable(hsh)
def __init__(self): env = Environment.getInstance() self.log = logging.getLogger(__name__) self.log.debug("initializing AMQP handler") self.env = env self.config = env.config # Initialize parser schema_root = etree.XML(PluginRegistry.getEventSchema()) schema = etree.XMLSchema(schema_root) self._parser = objectify.makeparser(schema=schema) # Evaluate username user = self.config.get("amqp.id", default=None) if not user: user = self.env.uuid password = self.config.get("amqp.key") # Load configuration self.url = parseURL(makeAuthURL(self.config.get('amqp.url'), user, password)) self.reconnect = self.config.get('amqp.reconnect', True) self.reconnect_interval = self.config.get('amqp.reconnect_interval', 3) self.reconnect_limit = self.config.get('amqp.reconnect_limit', 0) # Go for it self.start()
def __init__(self): super(MQTTClientHandler, self).__init__() e = EventMaker() goodbye = e.Event(e.ClientLeave(e.Id(Environment.getInstance().uuid))) self.will_set("%s/client/%s" % (self.domain, self.env.uuid), goodbye, qos=2)
def get_server_url(): """ Return the public URL of this GOsa server """ env = Environment.getInstance() gosa_server = env.config.get("jsonrpc.url")[0:-4] if env.config.get("jsonrpc.url") is not None else None if gosa_server is None: gosa_server = get_internal_server_url() return gosa_server
def use_test_config(request): Environment.reset() Environment.config = os.path.join( os.path.dirname(os.path.realpath(__file__)), "..", "test_conf") Environment.noargs = True env = Environment.getInstance() if has_dbus: # Enable DBus runner dr = DBusRunner() dr.start() PluginRegistry(component='gosa.client.module') # @UnusedVariable env.active = True def shutdown(): env.active = False # Wait for threads to shut down for t in env.threads: if hasattr(t, 'stop'): t.stop() if hasattr(t, 'cancel'): t.cancel() t.join(2) PluginRegistry.shutdown() if has_dbus: dr.stop() request.addfinalizer(shutdown)
def get_internal_server_url(): env = Environment.getInstance() host = socket.getfqdn() if env.config.get("http.host", default="localhost") in ["0.0.0.0", "127.0.0.1"] \ else env.config.get("http.host", default="localhost") ssl = env.config.getboolean('http.ssl') protocol = "https" if ssl is True else "http" return "%s://%s:%s" % (protocol, host, env.config.get('http.port', default=8050))
def __init__(self): self.env = Environment.getInstance() self.ldap_handler = LDAPHandler.get_instance() self.nfs_root = self.env.config.get("nfs_root", default="/srv/nfsroot") self.nfs_opts = self.env.config.get("nfs_opts", default="nfs4") self.fai_flags = self.env.config.get("fai_flags", default="verbose,sshd,syslogd,createvt,reboot") self.union = self.env.config.get("union", default="unionfs")
def setUp(self): """ Stuff to be run before every test """ Environment.config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test-libinst.conf") Environment.noargs = True self.env = Environment.getInstance() self.mgr = LibinstManager() engine = self.env.getDatabaseEngine("repository") keyring = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) lQHYBEx2RJ8BBADGAvwUiutOLO+OgkpWmOfNczRcEWZSja8jfZJFAHkSknq7t9lM FD0qYkjxnmGvi44cPmKu7Z2xkBxljyKK5pDOkCqB2QBUrXSnb3rg6/w9gX8Mh1er e8VZ/45sjxqwoUIPWWsrmEotQ9388KbEhdw14FQj/rai/Xa7rqYI6nVQSQARAQAB AAP6AyHggTljDsfnvu3ZQj/ihdj27A056XmOJ4elkobqNpfsdI9l8t3fy4dFvy28 8gKvnzG08uG1iyD1mnBho/sdytTKe7GMLDcHyWWBOl31WLKUzQFTOpQ6EjzKNyNl CGvwSKBm8u81BfNi7FpfgnVI733jdqZ8Lvq5znKRrK4WJdECANOaZn78oghTONUQ 1Fo6PgrjFkD337TR3Dm5tllp0Mlly9C9/N5CiTZj/0VLNyzT0tHVik8WEmF37bgY Zd2gA9kCAO+Oj6k9Bqs6uTjHFmT5NEGvoJVSd4Q+F4jDmT+U2yJEBUk1dHiRAcEr NcRU5VMbpBk9rbsmikX0oA1gavaNmfECAJi9uX99nb+dNWpqFqHxuDKaHapG9cKv AlI+btxIAzPFvqMuHMjFKn6T57D8QpIz1f7LdmlYKKOr3DRmaYOaJBClOrQ2QXV0 b2dlbmVyYXRlZCBLZXkgKEdlbmVyYXRlZCBieSBnbnVwZy5weSkgPGphbndAaG9t ZXI+iLgEEwECACIFAkx2RJ8CGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ ELxLvnLaEqJwX2oD/2wAOYbZG68k7iDOqFI1TpQjlgRQKHNuvindjWrPjfgsDfZH kEhidYX1IRzgyhhLjrPDcB0RTcnjlXm9xOXJb3tcuyKWxi2CHMstdgTMHt6xb37o LcWMU6gayNYj7eMgCOFM6ywySRS81FC+PPnr147xbp5FwgmoPRK52MURsHJ+ =RwlJ -----END PGP PRIVATE KEY BLOCK-----""" self.assertTrue(self.mgr.addKeys(keyring)) self.helperAddRepositoryTypes() self.assertTrue(self.mgr.createDistribution("debian", "deb")) self.assertTrue(self.mgr.createRelease("debian", "lenny")) self.assertTrue(self.mgr.createRelease("debian", "lenny/5.0.4")) self.assertTrue(self.mgr.createRelease("debian", "squeeze"))
def check_auth(user, password, get_dn=False): get = Environment.getInstance().config.get log = logging.getLogger(__name__) url = ldapurl.LDAPUrl(get("ldap.url")) bind_user = get('ldap.bind-user', default=None) bind_dn = get('ldap.bind-dn', default=None) bind_secret = get('ldap.bind-secret', default=None) conn = ldap.ldapobject.ReconnectLDAPObject( "%s://%s" % (url.urlscheme, url.hostport), retry_max=int(get("ldap.retry-max", default=3)), retry_delay=int(get("ldap.retry-delay", default=5))) # We only want v3 conn.protocol_version = ldap.VERSION3 # If no SSL scheme used, try TLS if get("ldap.tls", default="True").lower( ) == "true" and ldap.TLS_AVAIL and url.urlscheme != "ldaps": try: conn.start_tls_s() except ldap.PROTOCOL_ERROR as detail: log.debug("cannot use TLS, falling back to unencrypted session") try: # Get a connection if bind_dn: log.debug("starting simple bind using '%s'" % bind_dn) conn.simple_bind_s(bind_dn, bind_secret) elif bind_user: log.debug("starting SASL bind using '%s'" % bind_user) auth_tokens = ldap.sasl.digest_md5(bind_user, bind_secret) conn.sasl_interactive_bind_s("", auth_tokens) else: log.debug("starting anonymous bind") conn.simple_bind_s() # Search for the given user UID res = conn.search_s( url.dn, ldap.SCOPE_SUBTREE, filter_format( "(|(&(objectClass=registeredDevice)(deviceUUID=%s))(&(objectClass=person)(uid=%s)))", [user, user]), ['dn']) if len(res) == 1: dn = res[0][0] log.debug("starting simple bind using '%s'" % dn) conn.simple_bind_s(dn, password) return True if not get_dn else dn elif len(res) > 1: log.error("LDAP authentication failed: user %s not unique" % user) else: log.error("LDAP authentication failed: user %s not found" % user) except ldap.INVALID_CREDENTIALS as detail: log.error("LDAP authentication failed: %s" % str(detail)) return False
def __init__(self, autostart=True, host=None, port=None, keepalive=None): """ Construct a new MQTTClientHandler instance based on the configuration stored in the environment. @type env: Environment @param env: L{Environment} object """ self.log = logging.getLogger(__name__) self.log.debug("initializing MQTT client handler") self.env = Environment.getInstance() # Load configuration self.host = self.env.config.get('mqtt.host') if host is None else host if port is not None: self.port = port else: self.port = int(self.env.config.get('mqtt.port', default=1883)) \ if self.env.config.get('mqtt.port', default=1883) is not None else 1883 # Auto detect if possible if not self.host: svcs = find_bus_service() if svcs: self.host, self.port = svcs[0] # Bail out? if not self.host: self.log.error("no MQTT host available for bus communication") raise Exception("no MQTT host available") self.keep_alive = self.env.config.get('mqtt.keepalive', default=60) if keepalive is None else keepalive self.domain = self.env.domain domain_parts = socket.getfqdn().split('.', 1) self.dns_domain = domain_parts[1] if len(domain_parts) == 2 else "local" # Check if credentials are supplied if not self.env.config.get("jsonrpc.key") and not hasattr(self.env, "core_key"): raise Exception("no key supplied - please join the client") # Configure system if hasattr(self.env, "core_uuid") and hasattr(self.env, "core_key"): user = self.env.core_uuid key = self.env.core_key else: user = self.env.uuid key = self.env.config.get('jsonrpc.key') # Make proxy connection self.log.info("using service '%s:%s'" % (self.host, self.port)) self.__client = MQTTClient(self.host, port=self.port, keepalive=self.keep_alive) self.__client.authenticate(user, key) self.init_subscriptions() if autostart: # Start connection self.start()
def test_generateUid(self): user = TestUser() assert user is not None env = Environment.getInstance().config # enable test when using gosa's transliterate with mock.patch.object(env, 'get') as mock_config: mock_config.return_value = '{%sn}' assert user.generateUid({'sn': 'SmÜrübröd'}) == ['SmUeruebroed'] mock_config.return_value = '{%prename} {%sn}' assert user.generateUid({'prename': 'Владимир', 'sn': 'Путин'}) == ['Vladimir Putin'] mock_config.return_value = '{%sn}' assert user.generateUid({'sn': 'Doe'}) == ['Doe'] assert user.generateUid({'sn': 'Dorian'}) == ['Dorian'] mock_config.return_value = '{%sn}-{%prename}' assert user.generateUid({'sn': 'Doe', 'prename': 'John'}) == ['Doe-John'] mock_config.return_value = '{%sn[1]}' assert user.generateUid({'sn': 'Doe'}) == ['o'] mock_config.return_value = '{%sn[1-3]}' assert user.generateUid({'sn': 'Dorian'}) == ['o', 'or'] mock_config.return_value = '{%prename}-{%sn[1-3]}' assert user.generateUid({'sn': 'Dorian', 'prename': 'John'}) == ['John-o', 'John-or'] mock_config.return_value = '{%prename[1-3]}-{%sn[1-3]}' assert user.generateUid({'sn': 'Dorian', 'prename': 'John'}) == ['o-o', 'o-or', 'oh-o', 'oh-or'] mock_config.return_value = '{%Sn}' assert user.generateUid({'Sn': 'Doe'}) == ['Doe'] mock_config.return_value = '{%sn}-{id:3}' assert user.generateUid({'sn': 'doe'}) == ['doe-000'] user.existing_uids = ['doe-000', 'doe-001', 'doe-002'] mock_config.return_value = '{%sn}-{id:3}' assert user.generateUid({'sn': 'doe'}) == ['doe-003'] mock_config.return_value = '{%sn[0-3]}-{id:3}' assert user.generateUid({'sn': 'doe'}) == ['d-000', 'do-000', 'doe-003'] mock_config.return_value = '{id#3}' random_id = user.generateUid(None)[0] assert len(random_id) == 3 assert int(random_id) >= 100 assert int(random_id) < 1000 mock_config.return_value = '{%sn}{id!2}' user.existing_uids = [] assert user.generateUid({'sn': 'doe'}) == ['doe'] user.existing_uids = ['doe'] assert user.generateUid({'sn': 'doe'}) == ['doe01'] user.existing_uids = ['doe', 'doe01'] assert user.generateUid({'sn': 'doe'}) == ['doe02'] user.existing_uids = ['doe01'] assert user.generateUid({'sn': 'doe'}) == ['doe'] mock_config.return_value = '{%sn}' user.existing_uids = ['doe'] assert user.generateUid({'sn': 'doe'}) == []
def setUp(self): super(MQTTRelayServiceTestCase, self).setUp() self.env = Environment.getInstance() self.env.core_uuid = str(uuid.uuid4()) self.service = MQTTRelayService() self.service.serve() PluginRegistry.modules["ACLResolver"] = mock.MagicMock() PluginRegistry.modules["ObjectIndex"] = mock.MagicMock()
def get_server_url(): """ Return the public URL of this GOsa server """ env = Environment.getInstance() gosa_server = env.config.get("jsonrpc.url")[0:-4] if env.config.get( "jsonrpc.url") is not None else None if gosa_server is None: gosa_server = get_internal_server_url() return gosa_server
def __init__(self): env = Environment.getInstance() self.log = logging.getLogger(__name__) self.log.debug("initializing scheduler service") self.env = env self.sched = Scheduler() self.sched.daemonic = True self.sched.add_jobstore(RAMJobStore(), 'ram', True)
def __init__(self): env = Environment.getInstance() self.env = env self.__dr = DBusRunner.get_instance() self.__bus = None # Register for resume events zope.event.subscribers.append(self.__handle_events)
def initialize(self): env = Environment.getInstance() default = PluginRegistry.getInstance('HTTPService').get_gui_uri()[1] path = frontend_path if env.config.get("gui.debug", "false") == "false": # pragma: nocover path = os.path.join(frontend_path, 'gosa', 'build') super(GuiPlugin, self).initialize(path, default)
def __init__(self): env = Environment.getInstance() self.env = env self.log = logging.getLogger(__name__) # Register ourselfs for bus changes on org.gosa dr = DBusRunner.get_instance() self.bus = dr.get_system_bus() self.bus.watch_name_owner("org.gosa", self.__dbus_proxy_monitor)
def __init__(self): self.env = Environment.getInstance() # Load container mapping from object Factory factory = ObjectFactory.getInstance() self.containers = [] for ot, info in factory.getObjectTypes().items(): if 'container' in info: self.containers.append(ot)
def __init__(self): env = Environment.getInstance() self.env = env self.__dr = DBusRunner.get_instance() self.__bus = None self.__notify_backend = env.config.getboolean("client.dbus-login", default=True) # Register for resume events zope.event.subscribers.append(self.__handle_events)
def __init__(self): conn = get_system_bus() dbus.service.Object.__init__(self, conn, '/org/gosa/service') self.env = Environment.getInstance() self.log = logging.getLogger(__name__) self.systembus = dbus.SystemBus() systemd_obj = self.systembus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1") self.systemd = dbus.Interface(systemd_obj, "org.freedesktop.systemd1.Manager")
def __init__(self): env = Environment.getInstance() self.log = logging.getLogger(__name__) self.log.info("initializing HTTP service provider") self.env = env self.srv = None self.ssl = False self.host = None self.scheme = None self.port = None
def __init__(self, path, callback): # Initialize the plugin and set path self.bp = self.path = path self.callback = callback self.env = Environment.getInstance() self.log = logging.getLogger(__name__) # Start the files system surveillance thread now self.__start()