Ejemplo n.º 1
0
    def add_user_permission_group(self,
                                  permission_group,
                                  user_object,
                                  vm_object=None,
                                  ignore_duplicate=False):
        """Add a user to a permissions group on a VM object."""
        assert permission_group in PERMISSION_GROUPS.keys()
        assert isinstance(
            self._convert_remote_object(user_object),
            self._get_registered_object('user_factory').USER_CLASS)
        assert isinstance(
            self._convert_remote_object(vm_object),
            self._get_registered_object(
                'virtual_machine_factory').VIRTUAL_MACHINE_CLASS)
        ArgumentValidator.validate_boolean(ignore_duplicate)

        # Check if user running script is able to add users to permission group
        if not (self.is_superuser() or (vm_object and self.assert_permission(
                PERMISSIONS.MANAGE_VM_USERS, vm_object)
                                        and permission_group == 'user')):
            raise InsufficientPermissionsException(
                'VM owners cannot add manager other owners')

        user_object = self._convert_remote_object(user_object)
        vm_object = self._convert_remote_object(
            vm_object) if vm_object is not None else None
        username = user_object.get_username()

        # Check if user is already in the group
        if (vm_object):
            config_object = vm_object.get_config_object()
        else:
            config_object = MCVirtConfig()

        if (username not in self.get_users_in_permission_group(
                permission_group, vm_object)):

            # Add user to permission configuration for VM
            def add_user_to_config(config):
                config['permissions'][permission_group].append(username)

            config_object.update_config(
                add_user_to_config, 'Added user \'%s\' to group \'%s\'' %
                (username, permission_group))

            # @TODO FIX ME
            if self._is_cluster_master:
                cluster_object = self._get_registered_object('cluster')
                vm_name = vm_object.get_name() if vm_object else None
                cluster_object.run_remote_command(
                    'auth-add_user_permission_group', {
                        'permission_group': permission_group,
                        'username': username,
                        'vm_name': vm_name
                    })

        elif not ignore_duplicate:
            raise DuplicatePermissionException(
                'User \'%s\' already in group \'%s\'' %
                (username, permission_group))
Ejemplo n.º 2
0
    def delete_superuser(self, user_object):
        """Remove a superuser."""
        assert isinstance(self._convert_remote_object(user_object),
                          self._get_registered_object('user_factory').USER_CLASS)

        # Ensure the user is a superuser
        if not self.is_superuser():
            raise InsufficientPermissionsException(
                'User must be a superuser to manage superusers'
            )

        user_object = self._convert_remote_object(user_object)
        username = user_object.get_username()

        # Ensure user to be removed is a superuser
        if (username not in self.get_superusers()):
            raise UserNotPresentInGroup('User \'%s\' is not a superuser' % username)

        mcvirt_config = MCVirtConfig()

        def update_config(config):
            config['superusers'].remove(username)
        mcvirt_config.update_config(update_config, 'Removed \'%s\' from superuser group' %
                                                   username)

        if self._is_cluster_master:
            def remote_command(connection):
                remote_user_factory = connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(user_object.get_username())
                remote_auth = connection.get_connection('auth')
                remote_auth.delete_superuser(remote_user)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 3
0
 def get_config(self):
     """Return the global Drbd configuration"""
     mcvirt_config = MCVirtConfig()
     if 'drbd' in mcvirt_config.get_config().keys():
         return mcvirt_config.get_config()['drbd']
     else:
         return self.get_default_config()
Ejemplo n.º 4
0
 def get_config(self):
     """Return the global Drbd configuration"""
     mcvirt_config = MCVirtConfig()
     if 'drbd' in mcvirt_config.get_config().keys():
         return mcvirt_config.get_config()['drbd']
     else:
         return self.get_default_config()
Ejemplo n.º 5
0
    def delete_user_permission_group(self, permission_group, user_object, vm_object=None):
        """Remove user from a permissions group on a VM object."""
        assert permission_group in PERMISSION_GROUPS.keys()
        assert isinstance(self._convert_remote_object(user_object),
                          self._get_registered_object('user_factory').USER_CLASS)
        assert isinstance(self._convert_remote_object(vm_object),
                          self._get_registered_object(
                              'virtual_machine_factory').VIRTUAL_MACHINE_CLASS)
        # Check if user running script is able to remove users to permission group
        if not (self.is_superuser() or
                (self.assert_permission(PERMISSIONS.MANAGE_VM_USERS, vm_object) and
                 permission_group == 'user') and vm_object):
            raise InsufficientPermissionsException('Does not have required permission')

        user_object = self._convert_remote_object(user_object)
        username = user_object.get_username()

        # Check if user exists in the group
        if username not in self.get_users_in_permission_group(permission_group, vm_object):
            raise UserNotPresentInGroup('User \'%s\' not in group \'%s\'' %
                                        (username, permission_group))

        if vm_object:
            vm_object = self._convert_remote_object(vm_object)
            config_object = vm_object.get_config_object()
        else:
            config_object = MCVirtConfig()

        # Remove user from permission configuration for VM
        def remove_user_from_group(config):
            config['permissions'][permission_group].remove(username)

        config_object.update_config(remove_user_from_group,
                                    'Removed user \'%s\' from group \'%s\'' %
                                    (username, permission_group))

        if self._is_cluster_master:
            def add_remote_user_to_group(connection):
                remote_user_factory = connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(
                    user_object.get_username()
                )
                connection.annotate_object(remote_user)
                remote_auth = connection.get_connection('auth')
                if vm_object:
                    remote_vm_factory = connection.get_connection('virtual_machine_factory')
                    remote_vm = remote_vm_factory.getVirtualMachineByName(
                        vm_object.get_name()
                    )
                else:
                    remote_vm = None

                remote_auth.delete_user_permission_group(permission_group, remote_user, remote_vm)
            cluster_object = self._get_registered_object('cluster')
            cluster_object.run_remote_command(add_remote_user_to_group)
Ejemplo n.º 6
0
    def delete_user_permission_group(self,
                                     permission_group,
                                     user_object,
                                     vm_object=None):
        """Remove user from a permissions group on a VM object."""
        assert permission_group in PERMISSION_GROUPS.keys()
        assert isinstance(
            self._convert_remote_object(user_object),
            self._get_registered_object('user_factory').USER_CLASS)
        assert isinstance(
            self._convert_remote_object(vm_object),
            self._get_registered_object(
                'virtual_machine_factory').VIRTUAL_MACHINE_CLASS)
        # Check if user running script is able to remove users to permission group
        if not (self.is_superuser() or
                (self.assert_permission(PERMISSIONS.MANAGE_VM_USERS, vm_object)
                 and permission_group == 'user') and vm_object):
            raise InsufficientPermissionsException(
                'Does not have required permission')

        user_object = self._convert_remote_object(user_object)
        vm_object = self._convert_remote_object(
            vm_object) if vm_object is not None else None
        username = user_object.get_username()

        # Check if user exists in the group
        if username not in self.get_users_in_permission_group(
                permission_group, vm_object):
            raise UserNotPresentInGroup('User \'%s\' not in group \'%s\'' %
                                        (username, permission_group))

        if vm_object:
            config_object = vm_object.get_config_object()
            vm_name = vm_object.get_name()
        else:
            config_object = MCVirtConfig()
            vm_name = None

        # Remove user from permission configuration for VM
        def remove_user_from_group(config):
            config['permissions'][permission_group].remove(username)

        config_object.update_config(
            remove_user_from_group, 'Removed user \'%s\' from group \'%s\'' %
            (username, permission_group))

        # @TODO FIX ME
        if self._is_cluster_master:
            cluster_object = self._get_registered_object('cluster')
            cluster_object.run_remote_command(
                'auth-delete_user_permission_group', {
                    'permission_group': permission_group,
                    'username': username,
                    'vm_name': vm_name
                })
Ejemplo n.º 7
0
    def set_cluster_ip_address(self, ip_address):
        """Update the cluster IP address for the node."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        ArgumentValidator.validate_ip_address(ip_address)

        # Update global MCVirt configuration
        def update_config(config):
            config['cluster']['cluster_ip'] = ip_address
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config, 'Set node cluster IP address to %s' %
                                                   ip_address)
Ejemplo n.º 8
0
    def set_cluster_ip_address(self, ip_address):
        """Update the cluster IP address for the node."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        ArgumentValidator.validate_ip_address(ip_address)

        # Update global MCVirt configuration
        def update_config(config):
            config['cluster']['cluster_ip'] = ip_address
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config, 'Set node cluster IP address to %s' %
                                                   ip_address)
Ejemplo n.º 9
0
    def set_storage_volume_group(self, volume_group):
        """Update the MCVirt configuration to set the volume group for VM storage."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        ArgumentValidator.validate_vg_name(volume_group)

        # Update global MCVirt configuration
        def update_config(config):
            config['vm_storage_vg'] = volume_group
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config,
                                    'Set virtual machine storage volume group to %s' %
                                    volume_group)
Ejemplo n.º 10
0
    def set_storage_volume_group(self, volume_group):
        """Update the MCVirt configuration to set the volume group for VM storage."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        ArgumentValidator.validate_vg_name(volume_group)

        # Update global MCVirt configuration
        def update_config(config):
            config['vm_storage_vg'] = volume_group
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config,
                                    'Set virtual machine storage volume group to %s' %
                                    volume_group)
Ejemplo n.º 11
0
    def add_user_permission_group(self, permission_group, user_object,
                                  vm_object=None, ignore_duplicate=False):
        """Add a user to a permissions group on a VM object."""
        assert permission_group in PERMISSION_GROUPS.keys()
        assert isinstance(self._convert_remote_object(user_object),
                          self._get_registered_object('user_factory').USER_CLASS)
        assert isinstance(self._convert_remote_object(vm_object),
                          self._get_registered_object(
                              'virtual_machine_factory').VIRTUAL_MACHINE_CLASS)
        ArgumentValidator.validate_boolean(ignore_duplicate)

        # Check if user running script is able to add users to permission group
        if not (self.is_superuser() or
                (vm_object and self.assert_permission(PERMISSIONS.MANAGE_VM_USERS,
                                                      vm_object) and
                 permission_group == 'user')):
            raise InsufficientPermissionsException('VM owners cannot add manager other owners')

        user_object = self._convert_remote_object(user_object)
        vm_object = self._convert_remote_object(vm_object) if vm_object is not None else None
        username = user_object.get_username()

        # Check if user is already in the group
        if (vm_object):
            config_object = vm_object.get_config_object()
        else:
            config_object = MCVirtConfig()

        if (username not in self.get_users_in_permission_group(permission_group, vm_object)):

            # Add user to permission configuration for VM
            def add_user_to_config(config):
                config['permissions'][permission_group].append(username)

            config_object.update_config(add_user_to_config, 'Added user \'%s\' to group \'%s\'' %
                                                            (username, permission_group))

            # @TODO FIX ME
            if self._is_cluster_master:
                cluster_object = self._get_registered_object('cluster')
                vm_name = vm_object.get_name() if vm_object else None
                cluster_object.run_remote_command('auth-add_user_permission_group',
                                                  {'permission_group': permission_group,
                                                   'username': username,
                                                   'vm_name': vm_name})

        elif not ignore_duplicate:
            raise DuplicatePermissionException(
                'User \'%s\' already in group \'%s\'' % (username, permission_group)
            )
Ejemplo n.º 12
0
    def check_permission(self,
                         permission_enum,
                         vm_object=None,
                         user_object=None):
        """Check that the user has a given permission, either globally through MCVirt or for a
        given VM.
        """
        if 'STARTUP_PERIOD' in dir(Pyro4.current_context
                                   ) and Pyro4.current_context.STARTUP_PERIOD:
            return True

        if ('INTERNAL_REQUEST' in dir(Pyro4.current_context)
                and Pyro4.current_context.INTERNAL_REQUEST):
            return True

        # If the user is a superuser, all permissions are attached to the user
        if self.is_superuser():
            return True

        if user_object is None:
            user_object = self._get_registered_object(
                'mcvirt_session').get_current_user_object()

        # Determine if the type of user has the permissions
        if permission_enum in user_object.PERMISSIONS:
            return True

        # Check the global permissions configuration to determine
        # if the user has been granted the permission
        mcvirt_config = MCVirtConfig()
        mcvirt_permissions = mcvirt_config.getPermissionConfig()
        if self.check_permission_in_config(mcvirt_permissions,
                                           user_object.get_username(),
                                           permission_enum):
            return True

        # If a vm_object has been passed, check the VM
        # configuration file for the required permissions
        if vm_object:
            vm_config_object = vm_object.get_config_object()
            vm_config = vm_config_object.getPermissionConfig()

            # Determine if the user has been granted the required permissions
            # in the VM configuration file
            if (self.check_permission_in_config(vm_config,
                                                user_object.get_username(),
                                                permission_enum)):
                return True

        return False
Ejemplo n.º 13
0
 def get_free_vg_space(self):
     """Returns the free space in megabytes."""
     _, out, err = System.runCommand(['vgs', MCVirtConfig().get_config()['vm_storage_vg'],
                                      '-o', 'free', '--noheadings', '--nosuffix', '--units',
                                      'm'], False,
                                     DirectoryLocation.BASE_STORAGE_DIR)
     return float(out)
Ejemplo n.º 14
0
 def remove_node_configuration(self, node_name):
     """Remove an MCVirt node from the configuration and regenerates
     authorized_keys file
     """
     def remove_node_config(mcvirt_config):
         del(mcvirt_config['cluster']['nodes'][node_name])
     MCVirtConfig().update_config(remove_node_config)
Ejemplo n.º 15
0
    def get_connection(self, bind_dn=None, password=None):
        """Return an LDAP object"""
        if not LdapFactory.is_enabled():
            raise LdapNotEnabledException('Ldap has not been configured on this node')

        ca_cert_exists = os.path.exists(self.ldap_ca_cert_path)
        ldap_config = MCVirtConfig().get_config()['ldap']

        ldap.set_option(
            ldap.OPT_X_TLS_CACERTFILE,
            self.ldap_ca_cert_path if ca_cert_exists else ''
        )

        if bind_dn is None and password is None:
            bind_dn = ldap_config['bind_dn']
            password = ldap_config['bind_pass']

        try:
            ldap_connection = ldap.initialize(uri=ldap_config['server_uri'])
            ldap_connection.bind_s(bind_dn, password)
        except:
            raise LdapConnectionFailedException(
                'Connection attempts to the LDAP server failed.'
            )

        return ldap_connection
Ejemplo n.º 16
0
    def set_cluster_ip_address(self, ip_address):
        """Update the cluster IP address for the node."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        # Check validity of IP address (mainly to ensure that )
        pattern = re.compile(r"^((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])[ (\[]?(\.|dot)"
                             "[ )\]]?){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))$")
        if not pattern.match(ip_address):
            raise InvalidIPAddressException('%s is not a valid IP address' % ip_address)

        # Update global MCVirt configuration
        def update_config(config):
            config['cluster']['cluster_ip'] = ip_address
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config, 'Set node cluster IP address to %s' %
                                                   ip_address)
Ejemplo n.º 17
0
    def get_users_in_permission_group(self, permission_group, vm_object=None):
        """Obtain a list of users in a given group, either in the global permissions or
        for a specific VM.
        """
        if vm_object:
            permission_config = vm_object.get_config_object(
            ).getPermissionConfig()
        else:
            mcvirt_config = MCVirtConfig()
            permission_config = mcvirt_config.getPermissionConfig()

        if permission_group in permission_config.keys():
            return permission_config[permission_group]
        else:
            raise InvalidPermissionGroupException(
                'Permission group \'%s\' does not exist' % permission_group)
Ejemplo n.º 18
0
    def add_node_configuration(self, node_name, ip_address, connection_user,
                               connection_password, ca_key):
        """Add MCVirt node to configuration, generates a cluster user on the remote node
        and stores credentials against node in the MCVirt configuration.
        """
        self._get_registered_object('auth').assert_permission(
            PERMISSIONS.MANAGE_CLUSTER)

        # Create CA file
        ssl_object = self._get_registered_object(
            'certificate_generator_factory').get_cert_generator(node_name)
        ssl_object.ca_pub_file = ca_key

        # Connect to node and obtain cluster user
        remote = Connection(username=connection_user,
                            password=connection_password,
                            host=node_name)
        remote_user_factory = remote.get_connection('user_factory')
        connection_user = remote_user_factory.get_user_by_username(
            connection_user)
        remote.annotate_object(connection_user)
        username, password = connection_user.create_cluster_user(
            host=get_hostname())

        # Add node to configuration file
        def add_node_config(mcvirt_config):
            mcvirt_config['cluster']['nodes'][node_name] = {
                'ip_address': ip_address,
                'username': username,
                'password': password
            }

        MCVirtConfig().update_config(add_node_config)
Ejemplo n.º 19
0
    def update_host(self, host):
        """Update the host associated with the user."""
        def update_config(config):
            config['users'][self.get_username()]['host'] = host

        MCVirtConfig().update_config(
            update_config, 'Updated host for \'%s\'' % self.get_username())
Ejemplo n.º 20
0
    def get_users_in_permission_group(self, permission_group, vm_object=None):
        """Obtain a list of users in a given group, either in the global permissions or
        for a specific VM.
        """
        if vm_object:
            permission_config = vm_object.get_config_object().getPermissionConfig()
        else:
            mcvirt_config = MCVirtConfig()
            permission_config = mcvirt_config.getPermissionConfig()

        if permission_group in permission_config.keys():
            return permission_config[permission_group]
        else:
            raise InvalidPermissionGroupException(
                'Permission group \'%s\' does not exist' % permission_group
            )
Ejemplo n.º 21
0
    def tearDown(self):
        """Reset any values changed to the MCVirt config"""
        def reset_config(config):
            config['cluster']['cluster_ip'] = self.original_ip_address
            config['vm_storage_vg'] = self.original_volume_group
        MCVirtConfig().update_config(reset_config, 'Reset node configurations')

        super(NodeTests, self).tearDown()
Ejemplo n.º 22
0
    def add_config(self, username, user_config):
        """Add a user config to the local node."""
        # Ensure this is being run as a Cluster User
        self._get_registered_object('auth').check_user_type('ClusterUser')

        def update_config(config):
            config['users'][username] = user_config
        MCVirtConfig().update_config(update_config, 'Adding user %s' % username)
Ejemplo n.º 23
0
    def setUp(self):
        """Create test Ldap configuration"""
        super(LdapTests, self).setUp()

        # Keep a copy of the original Ldap config so it can be restored in the tear down
        self.original_ldap_config = MCVirtConfig().get_config()['ldap']

        def update_config(config):
            config['ldap'] = LdapTests.TEST_LDAP_CONFIG

        MCVirtConfig().update_config(update_config,
                                     'Create test Ldap configuration')

        # Setup mock ldap
        self.mockldap.start()

        self.ldap_factory = LdapFactory()
Ejemplo n.º 24
0
 def get_all_usernames(cls):
     """Return all local users"""
     user_config = MCVirtConfig().get_config()['users']
     users = []
     for username in user_config:
         if user_config[username]['user_type'] == cls.__name__:
             users.append(username)
     return users
Ejemplo n.º 25
0
    def set_storage_volume_group(self, volume_group):
        """Update the MCVirt configuration to set the volume group for VM storage."""
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_NODE)

        # Ensure volume_group name is valid
        pattern = re.compile("^[A-Z0-9a-z_-]+$")
        if not pattern.match(volume_group):
            raise InvalidVolumeGroupNameException('%s is not a valid volume group name' %
                                                  volume_group)

        # Update global MCVirt configuration
        def update_config(config):
            config['vm_storage_vg'] = volume_group
        mcvirt_config = MCVirtConfig()
        mcvirt_config.update_config(update_config,
                                    'Set virtual machine storage volume group to %s' %
                                    volume_group)
Ejemplo n.º 26
0
 def get_log_level():
     """Return the log level, set either by environmental variable
     or configuration in MCVirt config
     """
     from mcvirt.mcvirt_config import MCVirtConfig
     if 'MCVIRT_DEBUG' in os.environ:
         return os.environ['MCVIRT_DEBUG'].upper()
     else:
         return MCVirtConfig().get_config()['log_level'].upper()
Ejemplo n.º 27
0
    def test_user_search(self):
        """Test that getting LDAP usernames takes the user_search attribute into account"""
        def update_config(config):
            config['ldap']['user_search'] = '(loginShell=/bin/bash)'

        MCVirtConfig().update_config(update_config, 'Set user_search')

        ldap_users = self.ldap_factory.get_all_usernames()
        self.assertTrue(LdapTests.TEST_USERS[0]['username'] in ldap_users)
        self.assertFalse(LdapTests.TEST_USERS[1]['username'] in ldap_users)
Ejemplo n.º 28
0
    def tearDown(self):
        """Restore the correct Ldap configuration"""
        def reset_config(config):
            config['ldap'] = self.original_ldap_config

        MCVirtConfig().update_config(reset_config, 'Reset Ldap configuration')

        # Stop mock ldap
        self.mockldap.stop()

        super(LdapTests, self).tearDown()
Ejemplo n.º 29
0
    def add_superuser(self, user_object, ignore_duplicate=False):
        """Add a new superuser."""
        assert isinstance(
            self._convert_remote_object(user_object),
            self._get_registered_object('user_factory').USER_CLASS)
        ArgumentValidator.validate_boolean(ignore_duplicate)

        # Ensure the user is a superuser
        if not self.is_superuser():
            raise InsufficientPermissionsException(
                'User must be a superuser to manage superusers')
        user_object = self._convert_remote_object(user_object)
        username = user_object.get_username()

        mcvirt_config = MCVirtConfig()

        # Ensure user is not already a superuser
        if username not in self.get_superusers():

            def update_config(config):
                config['superusers'].append(username)

            mcvirt_config.update_config(update_config,
                                        'Added superuser \'%s\'' % username)

        elif not ignore_duplicate:
            raise DuplicatePermissionException(
                'User \'%s\' is already a superuser' % username)

        if self._is_cluster_master:

            def remote_command(connection):
                remote_user_factory = connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(
                    user_object.get_username())
                remote_auth = connection.get_connection('auth')
                remote_auth.add_superuser(remote_user,
                                          ignore_duplicate=ignore_duplicate)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 30
0
    def sync_config(self, remote_connection):
        """Sync MCVirt configuration"""
        config = MCVirtConfig().get_config()
        remote_mcvirt_config_obj = remote_connection.get_connection('mcvirt_config')
        remote_config = remote_mcvirt_config_obj.get_config_remote()

        # Update Git and LDAP configuration to remote node
        remote_config['git'] = config['git']
        remote_config['ldap'] = config['ldap']
        remote_mcvirt_config_obj.manual_update_config(remote_config,
                                                      ('Update LDAP/Git configuration after'
                                                       ' joining node to cluster.'))
Ejemplo n.º 31
0
    def check_permission(self, permission_enum, vm_object=None, user_object=None):
        """Check that the user has a given permission, either globally through MCVirt or for a
        given VM.
        """
        if Pyro4.current_context.STARTUP_PERIOD:
            return True

        # If the user is a superuser, all permissions are attached to the user
        if self.is_superuser():
            return True

        if user_object is None:
            user_object = self._get_registered_object('mcvirt_session').get_current_user_object()

        # Determine if the type of user has the permissions
        if permission_enum in user_object.PERMISSIONS:
            return True

        # Check the global permissions configuration to determine
        # if the user has been granted the permission
        mcvirt_config = MCVirtConfig()
        mcvirt_permissions = mcvirt_config.getPermissionConfig()
        if self.check_permission_in_config(mcvirt_permissions, user_object.get_username(),
                                           permission_enum):
            return True

        # If a vm_object has been passed, check the VM
        # configuration file for the required permissions
        if vm_object:
            vm_config_object = vm_object.get_config_object()
            vm_config = vm_config_object.getPermissionConfig()

            # Determine if the user has been granted the required permissions
            # in the VM configuration file
            if (self.check_permission_in_config(vm_config, user_object.get_username(),
                                                permission_enum)):
                return True

        return False
Ejemplo n.º 32
0
    def create(self, username, password, user_type=LocalUser):
        """Create a user."""
        self._get_registered_object('auth').assert_permission(
            PERMISSIONS.MANAGE_USERS
        )

        if not user_type.CAN_CREATE:
            raise InvalidUserTypeException('Cannot create this type of user')

        if not password:
            raise BlankPasswordException('Password cannot be blank')

        # Ensure that username is not part of a reserved namespace
        for user_class in self.get_user_types():
            if (user_class is not user_type and
                    user_class.USER_PREFIX is not None and
                    username.startswith(user_class.USER_PREFIX)):
                raise InvalidUsernameException(
                    'Username is within a reserved namespace'
                )

        # Ensure that there is not a duplicate user
        if user_type._check_exists(username):
            raise UserAlreadyExistsException('There is a user with the same username \'%s\'' %
                                             username)

        # Ensure valid user type
        user_type = self.ensure_valid_user_type(user_type)

        # Generate password salt for user and hash password
        salt = user_type._generate_salt()
        hashed_password = user_type._hash_string(password, salt)

        # Create config for user and update MCVirt config
        user_config = user_type.get_default_config()
        user_config['password'] = hashed_password
        user_config['salt'] = salt
        user_config['user_type'] = user_type.__name__

        def update_config(config):
            config['users'][username] = user_config
        MCVirtConfig().update_config(update_config, 'Create user \'%s\'' % username)

        if user_type.DISTRIBUTED and self._is_cluster_master:
            # Create the user on the other nodes in the cluster
            def remote_command(node_connection):
                remote_user_factory = node_connection.get_connection('user_factory')
                remote_user_factory.create(username, password)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 33
0
    def delete_superuser(self, user_object):
        """Remove a superuser."""
        assert isinstance(
            self._convert_remote_object(user_object),
            self._get_registered_object('user_factory').USER_CLASS)

        # Ensure the user is a superuser
        if not self.is_superuser():
            raise InsufficientPermissionsException(
                'User must be a superuser to manage superusers')

        user_object = self._convert_remote_object(user_object)
        username = user_object.get_username()

        # Ensure user to be removed is a superuser
        if (username not in self.get_superusers()):
            raise UserNotPresentInGroup('User \'%s\' is not a superuser' %
                                        username)

        mcvirt_config = MCVirtConfig()

        def update_config(config):
            config['superusers'].remove(username)

        mcvirt_config.update_config(
            update_config, 'Removed \'%s\' from superuser group' % username)

        if self._is_cluster_master:

            def remote_command(connection):
                remote_user_factory = connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(
                    user_object.get_username())
                remote_auth = connection.get_connection('auth')
                remote_auth.delete_superuser(remote_user)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 34
0
    def add_superuser(self, user_object, ignore_duplicate=False):
        """Add a new superuser."""
        assert isinstance(self._convert_remote_object(user_object),
                          self._get_registered_object('user_factory').USER_CLASS)
        ArgumentValidator.validate_boolean(ignore_duplicate)

        # Ensure the user is a superuser
        if not self.is_superuser():
            raise InsufficientPermissionsException(
                'User must be a superuser to manage superusers'
            )
        user_object = self._convert_remote_object(user_object)
        username = user_object.get_username()

        mcvirt_config = MCVirtConfig()

        # Ensure user is not already a superuser
        if username not in self.get_superusers():
            def update_config(config):
                config['superusers'].append(username)
            mcvirt_config.update_config(update_config, 'Added superuser \'%s\'' % username)

        elif not ignore_duplicate:
            raise DuplicatePermissionException(
                'User \'%s\' is already a superuser' % username
            )

        if self._is_cluster_master:
            def remote_command(connection):
                remote_user_factory = connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(user_object.get_username())
                remote_auth = connection.get_connection('auth')
                remote_auth.add_superuser(remote_user, ignore_duplicate=ignore_duplicate)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 35
0
    def get_config(self):
        """Create the configuration for libvirt"""
        cert_gen_factory = self._get_registered_object('certificate_generator_factory')
        ssl_socket = cert_gen_factory.get_cert_generator('localhost')
        nodes = self._get_registered_object('cluster').get_nodes(return_all=True)
        nodes.append(get_hostname())
        allowed_dns = [cert_gen_factory.get_cert_generator(node).ssl_subj for node in nodes]

        return {
            'ip_address': MCVirtConfig().getListenAddress(),
            'ssl_server_key': ssl_socket.server_key_file,
            'ssl_server_cert': ssl_socket.server_pub_file,
            'ssl_ca_cert': ssl_socket.ca_pub_file,
            'allowed_nodes': '", "'.join(allowed_dns)
        }
Ejemplo n.º 36
0
    def get_all_usernames(self):
        """Return all users in the searchable LDAP directory"""
        if not LdapFactory.is_enabled():
            return []

        ldap_config = MCVirtConfig().get_config()['ldap']
        ldap_con = self.get_connection()

        try:
            res = ldap_con.search_s(ldap_config['base_dn'], ldap.SCOPE_SUBTREE,
                                    self.get_user_filter(),
                                    [str(ldap_config['username_attribute'])])
        except:
            raise UnknownLdapError(('An LDAP search error occurred. Please read the MCVirt'
                                    ' logs for more information'))
        return [user_obj[1][ldap_config['username_attribute']][0] for user_obj in res]
Ejemplo n.º 37
0
    def search_dn(self, username):
        """Determine a DN for a given username"""
        ldap_config = MCVirtConfig().get_config()['ldap']
        ldap_con = self.get_connection()

        try:
            res = ldap_con.search_s(str(ldap_config['base_dn']), ldap.SCOPE_SUBTREE,
                                    self.get_user_filter(username),
                                    [str(ldap_config['username_attribute'])])
        except:
            raise UnknownLdapError(('An LDAP search error occurred. Please read the MCVirt'
                                    ' logs for more information'))
        if len(res):
            return res[0][0]
        else:
            raise UserDoesNotExistException('User not returned by LDAP search')
Ejemplo n.º 38
0
    def set_enable(self, enable):
        """Flag as to whether LDAP authentication
        is enabled or disabled.
        """
        self._get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_USERS)

        def update_config(config):
            config['ldap']['enabled'] = enable
        MCVirtConfig().update_config(update_config, 'Updated LDAP status')

        if self._is_cluster_master:
            def remote_command(node_connection):
                remote_ldap_factory = node_connection.get_connection('ldap_factory')
                remote_ldap_factory.set_enable(enable)
            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 39
0
    def _set_password(self, new_password):
        """Set the password for the current user"""
        password_hash = self._hash_password(new_password)

        def update_config(config):
            config['users'][self.get_username()]['password'] = password_hash
        MCVirtConfig().update_config(
            update_config, 'Updated password for \'%s\'' % self.get_username()
        )

        if self.DISTRIBUTED and self._is_cluster_master:
            def remote_command(node_connection):
                remote_user_factory = node_connection.get_connection('user_factory')
                remote_user = remote_user_factory.get_user_by_username(self.get_username())
                node_connection.annotate_object(remote_user)
                remote_user.set_password(new_password)

            cluster = self._get_registered_object('cluster')
            cluster.run_remote_command(remote_command)
Ejemplo n.º 40
0
 def get_superusers(self):
     """Return a list of superusers"""
     mcvirt_config = MCVirtConfig()
     return mcvirt_config.get_config()['superusers']