Example #1
0
    def make_error(code, topic=None, details=None, **kwargs):

        # Add topic to make it usable inside of the error messages
        if not kwargs:
            kwargs = {}
        kwargs.update(dict(topic=topic))

        # Assemble message
        text = ClacksErrorHandler._codes[code] % kwargs

        # Assemble error information
        env = Environment.getInstance()
        db = env.get_mongo_db('clacks').errors
        data = dict(code=code, topic=topic, text=text,
                kwargs=kwargs, trace=traceback.format_stack(),
                details=details,
                timestamp=datetime.now(), user=None)

        # Write to db and update uuid
        __id = str(db.save(data))

        # First, catch unconverted exceptions
        if not code in ClacksErrorHandler._codes:
            return code

        return '<%s> %s' % (__id, text)
Example #2
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
        lm, nt = smbpasswd.hash(password)
        user = ObjectProxy(object_dn)
        user.sambaNTPassword = nt
        user.sambaLMPassword = lm
        user.commit()
Example #3
0
    def __init__(self, *args, **kwargs):
        self.log = logging.getLogger(__name__)
        self.env = Environment.getInstance()
        self.__secret = self.env.config.get('http.cookie-secret', default="TecloigJink4")
        self.__consumer = None

        super(WSHandler, self).__init__(*args, **kwargs)
Example #4
0
def main():
    env = Environment.getInstance()
    config = env.config

    # Load configuration
    path = config.get('backend-monitor.audit-log', default='/var/lib/clacks/ldap-audit.log')
    modifier = config.get('backend-monitor.modifier')
    user = config.get('core.id')
    password = config.get('amqp.key')
    url = parseURL(makeAuthURL(config.get('amqp.url'), user, password))

    # Connect to Clacks BUS
    proxy = AMQPServiceProxy(url['source'] + "/" + env.domain)

    # Main loop
    while True:
        sleep(1)

        # Wait for file to pop up
        if not os.path.exists(path):
            continue

        # Wait for file to be file
        if not os.path.isfile(path):
            continue

        # Check if it is effectively readable
        try:
            with open(path) as f:
                pass
        except IOError as e:
            continue

        # Listen for changes
        monitor(path, modifier, proxy)
Example #5
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": {"$size": 1}}, {"userPassword": 1})
        if res.count():
            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)
Example #6
0
    def setUp(self):
        """ Stuff to be run before every test """
        Environment.config = os.path.join(os.path.dirname(os.path.realpath(__file__)))
        Environment.noargs = True
        self.env = Environment.getInstance()
        self.mgr = LibinstManager()

        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"))
Example #7
0
    def __init__(self):
        self.env = env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.debug("initializing asterisk number resolver")

        self.__default_image = Image.open(pkg_resources.resource_filename("amires", "data/phone.png"))

        # Load resolver
        for entry in pkg_resources.iter_entry_points("phone.resolver"):
            module = entry.load()
            self.log.debug("loading resolver module '%s'" % module.__name__)
            obj = module()
            self.resolver[module.__name__] = {
                    'object': obj,
                    'priority': obj.priority,
            }

        # Load renderer
        for entry in pkg_resources.iter_entry_points("notification.renderer"):
            module = entry.load()
            self.log.debug("loading renderer module '%s'" % module.__name__)
            self.renderer[module.__name__] = {
                    'object': module(),
                    'priority': module.priority,
            }

        self.last_event = None
Example #8
0
    def setUserPassword(self, user, object_dn, password):
        """
        Set a new 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", "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 usind 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()
Example #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
Example #10
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()
Example #11
0
def main():
    """ Main programm which is called when the clacks agent process gets started.
        It does the main forking os related tasks. """

    # Set process list title
    os.putenv('SPT_NOENV', 'non_empty_value')
    setproctitle("clacks-agent")

    # Inizialize core environment
    env = Environment.getInstance()
    if not env.base:
        env.log.critical("Clacks agent needs a 'core.base' do operate on")
        exit(1)

    env.log.info("Clacks %s is starting up (server id: %s)" % (VERSION, env.id))

    if env.config.get('core.profile'):
        import cProfile
        import clacks.common.lsprofcalltree
        p = cProfile.Profile()
        p.runctx('mainLoop(env)', globals(), {'env': env})
        #pylint: disable=E1101
        k = clacks.common.lsprofcalltree.KCacheGrind(p)
        data = open('prof.kgrind', 'w+')
        k.output(data)
        data.close()
    else:
        mainLoop(env)
Example #12
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="clacks"))
        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) #@UndefinedVariable

        notifier = pyinotify.ThreadedNotifier(wm, PuppetLogWatcher())
        env.threads.append(notifier)

        notifier.start()
Example #13
0
    def __init__(self):
        conn = get_system_bus()
        dbus.service.Object.__init__(self, conn, '/org/clacks/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_clacks":
                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")
Example #14
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()
Example #15
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)
Example #16
0
    def __init__(self):
        self.env = env = Environment.getInstance()

        self.whitelisted_users = self.env.config.get("doingreport.users")
        if self.whitelisted_users:
            self.whitelisted_users = [s.strip() for s in self.whitelisted_users.split(",")]

        self.forge_url = self.env.config.get("fetcher-goforge.site-url", default="http://localhost/")
Example #17
0
    def __init__(self):
        """
        Construct a new AMQPClientHandler instance based on the configuration
        stored in the environment.

        @type env: Environment
        @param env: L{Environment} object
        """
        env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.debug("initializing AMQP client handler")
        self.env = env

        # Load configuration
        self.url = parseURL(self.env.config.get('amqp.url', None))
        self.domain = self.env.config.get('ampq.domain', default="org.clacks")
        self.dns_domain = socket.getfqdn().split('.', 1)[1]

        # Use zeroconf if there's no URL
        if self.url:
            o = urlparse(self.url['source'])

        else:
            url = ZeroconfClient.discover(['_amqps._tcp', '_amqp._tcp'],
                                          domain=self.domain)[0]
            o = urlparse(url)

            # pylint: disable=E1101
            self.domain = o.path[1::]

        # Configure system
        user = self.env.uuid

        key = self.env.config.get('amqp.key')
        if key:
            # pylint: disable=E1101
            self.url = parseURL(
                '%s://%s:%s@%s%s' % (o.scheme, user, key, o.netloc, o.path))
        else:
            self.url = parseURL(url)

        # Make proxy connection
        self.log.info(
            "using service '%s/%s'" % (self.url['host'], self.url['path']))
        self.__proxy = AMQPServiceProxy(self.url['source'])

        # Set params and go for it
        self.reconnect = self.env.config.get('amqp.reconnect', True)
        self.reconnect_interval = self.env.config.get(
            'amqp.reconnect-interval', 3)
        self.reconnect_limit = self.env.config.get('amqp.reconnect-limit', 0)

        # Check if credentials are supplied
        if not self.env.config.get("amqp.key"):
            raise Exception("no key supplied - please join the client")

        # Start connection
        self.start()
Example #18
0
    def __init__(self):
        self.env = Environment.getInstance()

        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)
Example #19
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)
Example #20
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 = filter(lambda y: not y.startswith("#"), [x.strip() for x in f.read().split("\n")])
Example #21
0
    def __init__(self):
        env = Environment.getInstance()
        self.env = env
        self.log = logging.getLogger(__name__)

        # Register ourselfs for bus changes on org.clacks
        dr = DBusRunner.get_instance()
        self.bus = dr.get_system_bus()
        self.bus.watch_name_owner("org.clacks", self.__dbus_proxy_monitor)
Example #22
0
    def searchForObjectDetails(self, user, extension, attribute, fltr, attributes, skip_values):
        """
        Search selectable items valid for the attribute "extension.attribute".

        This is used to add new groups to the users groupMembership attribute.
        """

        # Extract the the required information about the object
        # relation out of the BackendParameters for the given extension.
        of = ObjectFactory.getInstance()
        be_data = of.getObjectBackendParameters(extension, attribute)
        if not be_data:
            raise GOsaException(C.make_error("BACKEND_PARAMETER_MISSING", extension=extension, attribute=attribute))

        # Collection basic information
        otype, oattr, foreignMatchAttr, matchAttr = be_data[attribute] #@UnusedVariable

        # Create a list of attributes that will be requested
        if oattr not in attributes:
            attributes.append(oattr)
        attrs = dict([(x, 1) for x in attributes])
        if not "dn" in attrs:
            attrs.update({'dn': 1})

        # Start the query and brind the result in a usable form
        index = PluginRegistry.getInstance("ObjectIndex")
        res = index.search({
            '$or': [{'_type': otype}, {'_extensions': otype}],
            oattr: re.compile("^.*" + re.escape(fltr) + ".*$")
            }, attrs)
        result = []

        # Do we have read permissions for the requested attribute
        env = Environment.getInstance()
        topic = "%s.objects.%s" % (env.domain, otype)
        aclresolver = PluginRegistry.getInstance("ACLResolver")

        for entry in res:

            if not aclresolver.check(user, topic, "s", base=entry['dn']):
                continue

            item = {}
            for attr in attributes:
                if attr in entry and len(entry[attr]):
                    item[attr] = entry[attr] if attr == "dn" else entry[attr][0]
                else:
                    item[attr] = ""
            item['__identifier__'] = item[oattr]

            # Skip values that are in the skip list
            if skip_values and item['__identifier__'] in skip_values:
                continue

            result.append(item)

        return result
Example #23
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 ystem surveillance thread now
        self.__start()
Example #24
0
    def __init__(self):
        env = Environment.getInstance()
        self.env = env
        self.log = logging.getLogger(__name__)
        self.log.info("initializing JSON RPC service provider")
        self.path = self.env.config.get('jsonrpc.path', default="/rpc")

        self.__zeroconf = None
        self.__http = None
        self.__app = None
Example #25
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
Example #26
0
    def __init__(self, obj):
        super(ImageProcessor, self).__init__(obj)

        # Get mongo cache collection
        env = Environment.getInstance()
        self.db = env.get_mongo_db('clacks')

        # Ensure basic index for the objects
        for index in ['uuid', 'attribute', 'modified']:
            self.db.cache.ensure_index(index)
Example #27
0
 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 = None
     self.app = None
     self.host = None
     self.scheme = None
     self.port = None
Example #28
0
    def __init__(self):
        env = Environment.getInstance()
        self.env = env
        self.log = logging.getLogger(__name__)

        # Register ourselfs for bus changes on org.clacks
        dr = DBusRunner.get_instance()
        self.bus = dr.get_system_bus()
        self.bus.watch_name_owner("org.clacks", self.__dbus_proxy_monitor)

        # Create icon cache directory
        self.spool = env.config.get("client.spool", default="/var/spool/clacks")
Example #29
0
    def __init__(self):
        self.env = env = Environment.getInstance()

        # read replacement configuration
        if not PhoneNumberResolver.replace:
            for opt in env.config.getOptions("resolver-replace"):
                itm = env.config.get("resolver-replace.%s" % opt)
                res = re.search("^\"(.*)\",\"(.*)\"$", itm)
                res = re.search("^\"(.*)\"[\s]*,[\s]*\"(.*)\"$", itm)

                if res:
                    PhoneNumberResolver.replace.append([res.group(1), res.group(2)])
Example #30
0
    def __init__(self):
        env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.log.debug("initializing scheduler")
        self.env = env

        self.sched = Scheduler(origin=self.env.id)

        self.sched.add_jobstore(
            MongoDBJobStore(database="clacks", collection="scheduler", connection=self.env.get_mongo_connection()),
            "default",
        )
        self.sched.add_jobstore(RAMJobStore(), "ram", True)