Ejemplo n.º 1
0
Archivo: main.py Proyecto: gonicus/gosa
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
Ejemplo n.º 2
0
Archivo: main.py Proyecto: gonicus/gosa
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
Ejemplo n.º 3
0
def use_test_config():
    Environment.reset()
    Environment.config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "test_conf")
    Environment.noargs = True

    oreg = ObjectRegistry.getInstance()  # @UnusedVariable
    pr = PluginRegistry()  # @UnusedVariable
    cr = PluginRegistry.getInstance("CommandRegistry") # @UnusedVariable
Ejemplo n.º 4
0
 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)
     ))
Ejemplo n.º 5
0
Archivo: otp.py Proyecto: gonicus/gosa
 def available():
     # This should always work
     try:
         env = Environment.getInstance()
         return env.config.get("core.otp") is not None
     except:
         return False
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
 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
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
0
    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()
Ejemplo n.º 12
0
    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)
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
0
Archivo: main.py Proyecto: gonicus/gosa
    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")
Ejemplo n.º 15
0
    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()
Ejemplo n.º 16
0
 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()
Ejemplo n.º 17
0
    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()
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
    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")
Ejemplo n.º 20
0
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()
Ejemplo n.º 21
0
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))
Ejemplo n.º 22
0
    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()
Ejemplo n.º 23
0
 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]
Ejemplo n.º 24
0
 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")
Ejemplo n.º 25
0
Archivo: main.py Proyecto: gonicus/gosa
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)
Ejemplo n.º 26
0
    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()
Ejemplo n.º 27
0
 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()
Ejemplo n.º 28
0
    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"))
Ejemplo n.º 29
0
Archivo: mqtt.py Proyecto: gonicus/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)
Ejemplo n.º 30
0
 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
Ejemplo n.º 31
0
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)
Ejemplo n.º 32
0
    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()
Ejemplo n.º 33
0
Archivo: ldap.py Proyecto: peuter/gosa
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
Ejemplo n.º 34
0
Archivo: httpd.py Proyecto: GOsa3/gosa
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))
Ejemplo n.º 35
0
Archivo: httpd.py Proyecto: GOsa3/gosa
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
Ejemplo n.º 36
0
    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)
Ejemplo n.º 37
0
 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)
Ejemplo n.º 38
0
 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()
Ejemplo n.º 39
0
    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)
Ejemplo n.º 40
0
    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)
Ejemplo n.º 41
0
Archivo: main.py Proyecto: peuter/gosa
    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)
Ejemplo n.º 42
0
    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)
Ejemplo n.º 43
0
Archivo: httpd.py Proyecto: GOsa3/gosa
 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
Ejemplo n.º 44
0
Archivo: main.py Proyecto: peuter/gosa
 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")
Ejemplo n.º 45
0
    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()
Ejemplo n.º 46
0
    def __init__(self, _id, what=None, user=None, session_id=None):
        schema = etree.XMLSchema(
            file=resource_filename("gosa.backend", "data/workflow.xsd"))
        parser = objectify.makeparser(schema=schema)
        self.env = Environment.getInstance()
        self.parent = self
        self.uuid = _id
        self.dn = self.env.base
        self.__xml_parsing = XmlParsing('Workflows')
        self.__validator = Validator(self)
        self.__attribute_config = {}
        self.__user = user
        self.__session_id = session_id
        self.__log = logging.getLogger(__name__)
        self.__attribute_type = {}

        for entry in pkg_resources.iter_entry_points("gosa.object.type"):
            mod = entry.load()
            self.__attribute_type[mod.__alias__] = mod()

        self._path = self.env.config.get("core.workflow_path",
                                         "/var/lib/gosa/workflows")
        self._xml_root = objectify.parse(
            os.path.join(self._path, _id, "workflow.xml"), parser).getroot()

        self.__attribute = {key: None for key in self.get_attributes()}
        self.__method_map = {
            "commit": None,
            "get_templates": None,
            "get_translations": None,
        }
        self.__fill_method_map()

        if what is not None:
            # load object and copy attribute values to workflow
            try:
                self.__reference_object = ObjectProxy(what)

                self.__skip_refresh = True
                # set the reference dn if possible
                if 'reference_dn' in self.__attribute:
                    setattr(self, 'reference_dn', what)

                # copy all other available attribute values to workflow object
                for key in self.__attribute:
                    if hasattr(self.__reference_object, key) and getattr(
                            self.__reference_object, key) is not None:
                        setattr(self, key, getattr(self.__reference_object,
                                                   key))

                self.__skip_refresh = False

            except Exception as e:
                # could not open the reference object
                self.__log.error(e)
Ejemplo n.º 47
0
    def test_clientLeave(self):
        service = PluginRegistry.getInstance("MQTTRPCService")
        e = EventMaker()
        goodbye = e.Event(e.ClientLeave(e.Id("fake_uuid")))
        data = etree.tostring(goodbye).decode('utf-8')

        with mock.patch.object(PluginRegistry.getInstance("BackendRegistry"),
                               "unregisterBackend") as m:
            service.handle_request(
                "%s/proxy" % Environment.getInstance().domain, data)
            m.assert_called_with("fake_uuid")
Ejemplo n.º 48
0
    def test_send_event(self):
        mqtt = MQTTClientHandler()
        env = Environment.getInstance()

        with mock.patch("gosa.client.mqtt.MQTTHandler.send_event") as m:
            mqtt.send_event("test-data")
            m.assert_called_with("test-data", "%s/client/%s" % (env.domain, env.uuid), qos=0)

            m.reset_mock()
            mqtt.send_event("test-data", topic="test/topic")
            m.assert_called_with("test-data", "test/topic", qos=0)
Ejemplo n.º 49
0
 def __init__(self):
     """
     Construct a new ClientService instance based on the configuration
     stored in the environment.
     """
     env = Environment.getInstance()
     self.log = logging.getLogger(__name__)
     self.log.info("initializing client service")
     self.env = env
     self.__cr = None
     self.mqtt = None
Ejemplo n.º 50
0
    def __init__(self):
        self.__shells = {}

        # Use a shell source file
        env = Environment.getInstance()
        source = env.config.get('posix.shells', default="/etc/shells")

        with open(source) as f:
            self.__shells = list(
                filter(lambda y: not y.startswith("#"),
                       [x.strip() for x in f.read().split("\n")]))
Ejemplo n.º 51
0
def get_local_ppd_path(url):
    server_url = get_server_url()
    if url[0:len(server_url)] == server_url:
        http_part = "%s/ppd/modified/" % get_server_url()
        dir = Environment.getInstance().config.get("cups.spool",
                                                   default="/tmp/spool")
        return "%s/%s" % (dir, url[len(http_part):])
    elif url[0:1] == "/":
        # is already a local path
        return url
    return None
Ejemplo n.º 52
0
 def __init__(self):
     self.env = Environment.getInstance()
     self.log = logging.getLogger(__name__)
     # 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)
     self.__fuzzy_similarity_threshold = self.env.config.getfloat(
         "backend.fuzzy-threshold", default=0.3)
Ejemplo n.º 53
0
Archivo: main.py Proyecto: GOsa3/gosa
    def initialize(self):
        env = Environment.getInstance()
        default = PluginRegistry.getInstance('HTTPService').get_gui_uri()[1]
        path = frontend_path

        if env.config.get("gui.debug", "false") == "true":  # pragma: nocover
            path = os.path.realpath(
                os.path.join(
                    pkg_resources.resource_filename("gosa.plugins.gui", "data"), '..', '..', '..', '..', '..', 'frontend'
                )
            )
        super(GuiPlugin, self).initialize(path, default)
Ejemplo n.º 54
0
    def test_get_connection(self):
        handler = LDAPHandler()
        with pytest.raises(LDAPException),\
                mock.patch("gosa.backend.utils.ldap.LDAPHandler.connection_usage", new_callable=mock.PropertyMock, return_value=[True]):
            handler.get_connection()
        del handler

        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, pool-size, retry-max, retry-delay, tls
            m_env.return_value.config.get.side_effect = [
                ldap_url, 'admin', None, 'secret', 10, retry_max, retry_delay,
                tls
            ]
            handler = LDAPHandler()
            handler.get_connection()
            assert m_conn.return_value.sasl_interactive_bind_s.called
            del handler

            m_env.return_value.config.get.side_effect = [
                ldap_url, None, "bind-dn", 'secret', 10, retry_max,
                retry_delay, tls
            ]
            handler = LDAPHandler()
            handler.get_connection()
            m_conn.return_value.simple_bind_s.assert_called_with(
                "bind-dn", "secret")
            del handler

            m_env.return_value.config.get.side_effect = [
                ldap_url, None, None, None, 10, retry_max, retry_delay, tls
            ]
            handler = LDAPHandler()
            handler.get_connection()
            m_conn.return_value.simple_bind_s.assert_called_with()
            del handler

            m_conn.reset_mock()

            m_env.return_value.config.get.side_effect = [
                ldap_url, None, None, None, 10, retry_max, retry_delay, tls
            ]
            m_conn.return_value.simple_bind_s.side_effect = ldap.INVALID_CREDENTIALS(
                "test error")
            handler = LDAPHandler()
            with mock.patch.object(handler, "log") as m_log:
                handler.get_connection()
                assert m_log.error.called
            del handler
Ejemplo n.º 55
0
    def __init__(self):
        env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.debug("initializing scheduler")
        self.env = env

        self.sched = Scheduler()
        self.sched.add_jobstore(
            SQLAlchemyJobStore(
                engine=self.env.getDatabaseEngine("backend-database")),
            "default")
        self.sched.add_jobstore(RAMJobStore(), 'ram', True)
Ejemplo n.º 56
0
    def __init__(self):
        self.env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.uuid = dmi_system("uuid")
        self.mac = self.get_mac_address()
        try:
            self.domain = socket.getfqdn().split('.', 1)[1]
        except IndexError:
            self.log.warning("system has no proper DNS domain")
            self.domain = socket.getfqdn().split('.', 1)[0] + ".local"

        self.get_service()
Ejemplo n.º 57
0
Archivo: main.py Proyecto: peuter/gosa
    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)

        # Create icon cache directory
        self.spool = env.config.get("client.spool", default="/var/spool/gosa")
Ejemplo n.º 58
0
    def render(data):
        env = Environment.getInstance()

        cache_path = env.config.get('user.image-path',
                                    default="/var/lib/gosa/images")

        if os.path.exists(
                os.path.join(cache_path, data['_uuid'], "jpegPhoto", "0",
                             "64.jpg")):
            return "/images/%s/jpegPhoto/0/64.jpg?c=%s" % (
                data['_uuid'], data["_last_changed"])

        return "@Ligature/user"
Ejemplo n.º 59
0
Archivo: index.py Proyecto: peuter/gosa
    def __init__(self):
        self.env = Environment.getInstance()

        # Remove old lock if exists
        if GlobalLock.exists("scan_index"):
            GlobalLock.release("scan_index")

        self.log = logging.getLogger(__name__)
        self.log.info("initializing object index handler")
        self.factory = ObjectFactory.getInstance()

        # Listen for object events
        zope.event.subscribers.append(self.__handle_events)
Ejemplo n.º 60
0
Archivo: main.py Proyecto: peuter/gosa
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("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)
            mqtt.close()

        env.reset_requested = True
        env.active = False