Ejemplo n.º 1
0
    def authenticate(username, password):
        ldap_server = config.get("authentication", "ldap_server").strip('"')
        ldap_search_base = config.get(
            "authentication", "ldap_search_base").strip('"')
        ldap_search_filter = config.get(
            "authentication", "ldap_search_filter",
            vars={"username": username.encode("utf-8")}).strip('"')

        connect = ldap.open(ldap_server)
        try:
            result = connect.search_s(
                ldap_search_base, ldap.SCOPE_SUBTREE, ldap_search_filter)
            if len(result) == 0:
                entity = ldap_search_filter % {'username': username}
                raise ldap.LDAPError("Invalid ldap entity:%s" % entity)

            connect.bind_s(result[0][0], password)
            connect.unbind_s()
            return True
        except ldap.INVALID_CREDENTIALS:
                # invalid user password
            raise OperationFailed("KCHAUTH0002E")
        except ldap.NO_SUCH_OBJECT:
            # ldap search base specified wrongly.
            raise OperationFailed("KCHAUTH0005E", {"item": 'ldap_search_base',
                                                   "value": ldap_search_base})
        except ldap.LDAPError, e:
            arg = {"username": username, "code": e.message}
            raise OperationFailed("KCHAUTH0001E", arg)
Ejemplo n.º 2
0
    def lookup(self, *ident):
        report_tool = DebugReportsModel.get_system_report_tool()
        try:
            SoftwareUpdate()
        except Exception:
            update_tool = False
        else:
            update_tool = True

        try:
            repo = Repositories()
        except Exception:
            repo_mngt_tool = None
        else:
            repo_mngt_tool = repo._pkg_mnger.TYPE

        return {'libvirt_stream_protocols': self.libvirt_stream_protocols,
                'qemu_spice': self._qemu_support_spice(),
                'qemu_stream': self.qemu_stream,
                'screenshot': VMScreenshot.get_stream_test_result(),
                'system_report_tool': bool(report_tool),
                'update_tool': update_tool,
                'repo_mngt_tool': repo_mngt_tool,
                'federation': kconfig.get("server", "federation"),
                'auth': kconfig.get("authentication", "method"),
                'kernel_vfio': self.kernel_vfio,
                }
Ejemplo n.º 3
0
def new_ws_proxy():
    try:
        os.makedirs(WS_TOKENS_DIR, mode=0755)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass

    cert = config.get('server', 'ssl_cert')
    key = config.get('server', 'ssl_key')
    if not (cert and key):
        cert = '%s/kimchi-cert.pem' % paths.conf_dir
        key = '%s/kimchi-key.pem' % paths.conf_dir

    params = {'web': os.path.join(paths.ui_dir, 'pages/websockify'),
              'listen_port': config.get('display', 'display_proxy_port'),
              'target_cfg': WS_TOKENS_DIR,
              'key': key, 'cert': cert, 'ssl_only': True}

    def start_proxy():
        server = WebSocketProxy(**params)
        server.start_server()

    proc = Process(target=start_proxy)
    proc.start()
    return proc
Ejemplo n.º 4
0
    def authenticate(username, password):
        ldap_server = config.get("authentication", "ldap_server").strip('"')
        ldap_search_base = config.get("authentication",
                                      "ldap_search_base").strip('"')
        ldap_search_filter = config.get("authentication",
                                        "ldap_search_filter",
                                        vars={
                                            "username":
                                            username.encode("utf-8")
                                        }).strip('"')

        connect = ldap.open(ldap_server)
        try:
            result = connect.search_s(ldap_search_base, ldap.SCOPE_SUBTREE,
                                      ldap_search_filter)
            if len(result) == 0:
                entity = ldap_search_filter % {'username': username}
                raise ldap.LDAPError("Invalid ldap entity:%s" % entity)

            connect.bind_s(result[0][0], password)
            connect.unbind_s()
            return True
        except ldap.INVALID_CREDENTIALS:
            # invalid user password
            raise OperationFailed("KCHAUTH0002E")
        except ldap.NO_SUCH_OBJECT:
            # ldap search base specified wrongly.
            raise OperationFailed("KCHAUTH0005E", {
                "item": 'ldap_search_base',
                "value": ldap_search_base
            })
        except ldap.LDAPError, e:
            arg = {"username": username, "code": e.message}
            raise OperationFailed("KCHAUTH0001E", arg)
Ejemplo n.º 5
0
    def __init__(self, **kargs):
        # check federation feature is enabled on Kimchi server
        if config.get("server", "federation") == "off":
            return

        # register server on openslp
        hostname = socket.getfqdn(config.get("server", "host"))
        port = config.get("server", "ssl_port")
        self.url = hostname + ":" + port

        cmd = ["slptool", "register", "service:kimchid://%s" % self.url]
        out, error, ret = run_command(cmd)
        if out and len(out) != 0:
            kimchi_log.error("Unable to register server on openSLP."
                             " Details: %s" % out)
Ejemplo n.º 6
0
    def __init__(self, **kargs):
        # check federation feature is enabled on Kimchi server
        if config.get("server", "federation") == "off":
            return

        # register server on openslp
        hostname = socket.getfqdn(config.get("server", "host"))
        port = config.get("server", "ssl_port")
        self.url = hostname + ":" + port

        cmd = ["slptool", "register",
               "service:kimchid://%s" % self.url]
        out, error, ret = run_command(cmd)
        if len(out) != 0:
            kimchi_log.error("Unable to register server on openSLP."
                             " Details: %s" % out)
Ejemplo n.º 7
0
 def get_roles(self):
     admin_ids = config.get("authentication",
                            "ldap_admin_id").strip('"').split(',')
     for admin_id in admin_ids:
         if self.user[USER_NAME] == admin_id.strip():
             self.user[USER_ROLES] = dict.fromkeys(tabs, 'admin')
     return self.user[USER_ROLES]
Ejemplo n.º 8
0
 def lookup(self, name):
     proxy_port = kconfig.get('display', 'display_proxy_port')
     return {
         'http_port': cherrypy.config.nginx_port,
         'display_proxy_port': proxy_port,
         'version': get_version()
     }
Ejemplo n.º 9
0
 def get_roles(self):
     admin_ids = config.get(
         "authentication", "ldap_admin_id").strip('"').split(',')
     for admin_id in admin_ids:
         if self.user[USER_NAME] == admin_id.strip():
             self.user[USER_ROLES] = dict.fromkeys(tabs, 'admin')
     return self.user[USER_ROLES]
Ejemplo n.º 10
0
    def _get_user(self, _user_id):
        ldap_server = config.get("authentication", "ldap_server").strip('"')
        ldap_search_base = config.get(
            "authentication", "ldap_search_base").strip('"')
        ldap_search_filter = config.get(
            "authentication", "ldap_search_filter",
            vars={"username": _user_id.encode("utf-8")}).strip('"')

        connect = ldap.open(ldap_server)
        try:
            result = connect.search_s(
                ldap_search_base, ldap.SCOPE_SUBTREE, ldap_search_filter)
            if len(result) == 0:
                raise NotFoundError("KCHAUTH0004E", {'user_id': _user_id})
            return result[0][1]
        except ldap.NO_SUCH_OBJECT:
            raise NotFoundError("KCHAUTH0004E", {'user_id': _user_id})
Ejemplo n.º 11
0
def new_ws_proxy():
    try:
        os.makedirs(WS_TOKENS_DIR, mode=0755)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass

    cert = config.get('server', 'ssl_cert')
    key = config.get('server', 'ssl_key')
    if not (cert and key):
        cert = '%s/kimchi-cert.pem' % paths.conf_dir
        key = '%s/kimchi-key.pem' % paths.conf_dir

    cmd = os.path.join(os.path.dirname(__file__), 'websockify.py')
    args = ['python', cmd, config.get('display', 'display_proxy_port'),
            '--target-config', WS_TOKENS_DIR, '--cert', cert, '--key', key,
            '--web', os.path.join(paths.ui_dir, 'pages/websockify'),
            '--ssl-only']
    p = subprocess.Popen(args, close_fds=True)
    return p
Ejemplo n.º 12
0
    def _get_user(self, _user_id):
        ldap_server = config.get("authentication", "ldap_server").strip('"')
        ldap_search_base = config.get("authentication",
                                      "ldap_search_base").strip('"')
        ldap_search_filter = config.get("authentication",
                                        "ldap_search_filter",
                                        vars={
                                            "username":
                                            _user_id.encode("utf-8")
                                        }).strip('"')

        connect = ldap.open(ldap_server)
        try:
            result = connect.search_s(ldap_search_base, ldap.SCOPE_SUBTREE,
                                      ldap_search_filter)
            if len(result) == 0:
                raise NotFoundError("KCHAUTH0004E", {'user_id': _user_id})
            return result[0][1]
        except ldap.NO_SUCH_OBJECT:
            raise NotFoundError("KCHAUTH0004E", {'user_id': _user_id})
Ejemplo n.º 13
0
    def _build_access_elem(self, users, groups):
        auth = config.get("authentication", "method")
        auth_elem = E.auth(type=auth)
        for user in users:
            auth_elem.append(E.user(user))

        for group in groups:
            auth_elem.append(E.group(group))

        access = E.access()
        access.append(auth_elem)
        return access
Ejemplo n.º 14
0
def new_ws_proxy():
    try:
        os.makedirs(WS_TOKENS_DIR, mode=0755)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass

    cmd = os.path.join(os.path.dirname(__file__), 'websockify.py')
    args = ['python', cmd, config.get('display', 'display_proxy_port'),
            '--target-config', WS_TOKENS_DIR]
    p = subprocess.Popen(args, close_fds=True)
    return p
Ejemplo n.º 15
0
    def _build_access_elem(self, users, groups):
        auth = config.get("authentication", "method")
        auth_elem = E.auth(type=auth)
        for user in users:
            auth_elem.append(E.user(user))

        for group in groups:
            auth_elem.append(E.group(group))

        access = E.access()
        access.append(auth_elem)
        return access
Ejemplo n.º 16
0
def new_ws_proxy():
    try:
        os.makedirs(WS_TOKENS_DIR, mode=0755)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass

    cert = config.get('server', 'ssl_cert')
    key = config.get('server', 'ssl_key')
    if not (cert and key):
        cert = '%s/kimchi-cert.pem' % paths.conf_dir
        key = '%s/kimchi-key.pem' % paths.conf_dir

    cmd = os.path.join(os.path.dirname(__file__), 'websockify.py')
    args = [
        'python', cmd,
        config.get('display', 'display_proxy_port'), '--target-config',
        WS_TOKENS_DIR, '--cert', cert, '--key', key, '--web',
        os.path.join(paths.ui_dir, 'pages/websockify'), '--ssl-only'
    ]
    p = subprocess.Popen(args, close_fds=True)
    return p
Ejemplo n.º 17
0
    def _check_default_pools(self):
        pools = {}

        default_pool = tmpl_defaults['storagepool']
        default_pool = default_pool.split('/')[2]

        pools[default_pool] = {}
        if default_pool == 'default':
            pools[default_pool] = {'path': '/var/lib/libvirt/images'}

        if config.get("server", "create_iso_pool") == "true":
            pools['ISO'] = {'path': '/var/lib/kimchi/isos'}

        error_msg = ("Please, check the configuration in %s/template.conf to "
                     "ensure it has a valid storage pool." % paths.conf_dir)

        conn = self.conn.get()
        for pool_name in pools:
            try:
                pool = conn.storagePoolLookupByName(pool_name)
            except libvirt.libvirtError, e:
                pool_path = pools[pool_name].get('path')
                if pool_path is None:
                    msg = "Fatal: Unable to find storage pool %s. " + error_msg
                    kimchi_log.error(msg % pool_name)
                    kimchi_log.error("Details: %s", e.message)
                    sys.exit(1)

                # Try to create the pool
                pool = E.pool(E.name(pool_name), type='dir')
                pool.append(E.target(E.path(pool_path)))
                xml = ET.tostring(pool)
                try:
                    pool = conn.storagePoolDefineXML(xml, 0)
                except libvirt.libvirtError, e:
                    msg = "Fatal: Unable to create storage pool %s. "
                    msg += error_msg
                    kimchi_log.error(msg % pool_name)
                    kimchi_log.error("Details: %s", e.message)
                    sys.exit(1)

                # Build and set autostart value to pool
                # Ignore error as the pool was already successfully created
                try:
                    # Add build step to make sure target directory created
                    # The build process may fail when the pool directory
                    # already exists on system
                    pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW)
                    pool.setAutostart(1)
                except:
                    pass
Ejemplo n.º 18
0
    def _check_default_pools(self):
        pools = {}

        default_pool = tmpl_defaults['storagepool']
        default_pool = default_pool.split('/')[2]

        pools[default_pool] = {}
        if default_pool == 'default':
            pools[default_pool] = {'path': '/var/lib/libvirt/images'}

        if config.get("server", "create_iso_pool") == "true":
            pools['ISO'] = {'path': '/var/lib/kimchi/isos'}

        error_msg = ("Please, check the configuration in %s/template.conf to "
                     "ensure it has a valid storage pool." % paths.conf_dir)

        conn = self.conn.get()
        for pool_name in pools:
            try:
                pool = conn.storagePoolLookupByName(pool_name)
            except libvirt.libvirtError, e:
                pool_path = pools[pool_name].get('path')
                if pool_path is None:
                    msg = "Fatal: Unable to find storage pool %s. " + error_msg
                    kimchi_log.error(msg % pool_name)
                    kimchi_log.error("Details: %s", e.message)
                    sys.exit(1)

                # Try to create the pool
                pool = E.pool(E.name(pool_name), type='dir')
                pool.append(E.target(E.path(pool_path)))
                xml = ET.tostring(pool)
                try:
                    pool = conn.storagePoolDefineXML(xml, 0)
                except libvirt.libvirtError, e:
                    msg = "Fatal: Unable to create storage pool %s. "
                    msg += error_msg
                    kimchi_log.error(msg % pool_name)
                    kimchi_log.error("Details: %s", e.message)
                    sys.exit(1)

                # Build and set autostart value to pool
                # Ignore error as the pool was already successfully created
                try:
                    # Add build step to make sure target directory created
                    # The build process may fail when the pool directory
                    # already exists on system
                    pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW)
                    pool.setAutostart(1)
                except:
                    pass
Ejemplo n.º 19
0
def new_ws_proxy():
    try:
        os.makedirs(WS_TOKENS_DIR, mode=0755)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass

    cmd = os.path.join(os.path.dirname(__file__), 'websockify.py')
    args = [
        'python', cmd,
        config.get('display', 'display_proxy_port'), '--target-config',
        WS_TOKENS_DIR
    ]
    p = subprocess.Popen(args, close_fds=True)
    return p
Ejemplo n.º 20
0
    def get_list(self):
        # check federation feature is enabled on Kimchi server
        if config.get("server", "federation") == "off":
            return []

        peers = []
        cmd = ["slptool", "findsrvs", "service:kimchid"]
        out, error, ret = run_command(cmd)
        for server in out.strip().split("\n"):
            match = re.match("service:kimchid://(.*?),.*", server)
            peer = match.group(1)
            if peer != self.url:
                peers.append("https://" + peer)

        return peers
Ejemplo n.º 21
0
def login(username, password, **kwargs):
    auth_args = {"auth_type": config.get("authentication", "method"), "username": username, "password": password}

    user = User.get(auth_args)
    if not user:
        debug("User cannot be verified with the supplied password")
        return None

    debug("User verified, establishing session")
    cherrypy.session.acquire_lock()
    cherrypy.session.regenerate()
    cherrypy.session[USER_NAME] = username
    cherrypy.session[USER_GROUPS] = user.get_groups()
    cherrypy.session[USER_ROLES] = user.get_roles()
    cherrypy.session[REFRESH] = time.time()
    cherrypy.session.release_lock()
    return user.get_user()
Ejemplo n.º 22
0
    def get_list(self):
        # check federation feature is enabled on Kimchi server
        if config.get("server", "federation") == "off":
            return []

        cmd = ["slptool", "findsrvs", "service:kimchid"]
        out, error, ret = run_command(cmd)
        if ret != 0:
            return []

        peers = []
        for server in out.strip().split("\n"):
            match = re.match("service:kimchid://(.*?),.*", server)
            peer = match.group(1)
            if peer != self.url:
                peers.append("https://" + peer)

        return peers
Ejemplo n.º 23
0
def login(username, password, **kwargs):
    auth_args = {'auth_type': config.get("authentication", "method"),
                 'username': username,
                 'password': password}

    user = User.get(auth_args)
    if not user:
        debug("User cannot be verified with the supplied password")
        return None

    debug("User verified, establishing session")
    cherrypy.session.acquire_lock()
    cherrypy.session.regenerate()
    cherrypy.session[USER_NAME] = username
    cherrypy.session[USER_GROUPS] = user.get_groups()
    cherrypy.session[USER_ROLES] = user.get_roles()
    cherrypy.session[REFRESH] = time.time()
    cherrypy.session.release_lock()
    return user.get_user()
Ejemplo n.º 24
0
 def _get_access_info(self, dom):
     users = groups = list()
     access_xml = (get_metadata_node(dom, "access",
                                     self.caps.metadata_support) or
                   """<access></access>""")
     access_info = dictize(access_xml)
     auth = config.get("authentication", "method")
     if ('auth' in access_info['access'] and
             ('type' in access_info['access']['auth'] or
              len(access_info['access']['auth']) > 1)):
         users = xpath_get_text(access_xml,
                                "/access/auth[@type='%s']/user" % auth)
         groups = xpath_get_text(access_xml,
                                 "/access/auth[@type='%s']/group" % auth)
     elif auth == 'pam':
         # Compatible to old permission tagging
         users = xpath_get_text(access_xml, "/access/user")
         groups = xpath_get_text(access_xml, "/access/group")
     return users, groups
Ejemplo n.º 25
0
 def _get_access_info(self, dom):
     users = groups = list()
     access_xml = (get_metadata_node(dom, "access",
                                     self.caps.metadata_support) or
                   """<access></access>""")
     access_info = dictize(access_xml)
     auth = config.get("authentication", "method")
     if ('auth' in access_info['access'] and
             ('type' in access_info['access']['auth'] or
              len(access_info['access']['auth']) > 1)):
         users = xpath_get_text(access_xml,
                                "/access/auth[@type='%s']/user" % auth)
         groups = xpath_get_text(access_xml,
                                 "/access/auth[@type='%s']/group" % auth)
     elif auth == 'pam':
         # Compatible to old permission tagging
         users = xpath_get_text(access_xml, "/access/user")
         groups = xpath_get_text(access_xml, "/access/group")
     return users, groups
Ejemplo n.º 26
0
    def _build_access_elem(self, dom, users, groups):
        auth = config.get("authentication", "method")
        access_xml = get_metadata_node(dom, "access",
                                       self.caps.metadata_support)

        auth_elem = None

        if not access_xml:
            # there is no metadata element 'access'
            access_elem = E.access()
        else:
            access_elem = ET.fromstring(access_xml)

            same_auth = access_elem.xpath('./auth[@type="%s"]' % auth)
            if len(same_auth) > 0:
                # there is already a sub-element 'auth' with the same type;
                # update it.
                auth_elem = same_auth[0]

                if users is not None:
                    for u in auth_elem.findall('user'):
                        auth_elem.remove(u)

                if groups is not None:
                    for g in auth_elem.findall('group'):
                        auth_elem.remove(g)

        if auth_elem is None:
            # there is no sub-element 'auth' with the same type
            # (or no 'auth' at all); create it.
            auth_elem = E.auth(type=auth)
            access_elem.append(auth_elem)

        if users is not None:
            for u in users:
                auth_elem.append(E.user(u))

        if groups is not None:
            for g in groups:
                auth_elem.append(E.group(g))

        return access_elem
Ejemplo n.º 27
0
    def _build_access_elem(self, dom, users, groups):
        auth = config.get("authentication", "method")
        access_xml = get_metadata_node(dom, "access",
                                       self.caps.metadata_support)

        auth_elem = None

        if not access_xml:
            # there is no metadata element 'access'
            access_elem = E.access()
        else:
            access_elem = ET.fromstring(access_xml)

            same_auth = access_elem.xpath('./auth[@type="%s"]' % auth)
            if len(same_auth) > 0:
                # there is already a sub-element 'auth' with the same type;
                # update it.
                auth_elem = same_auth[0]

                if users is not None:
                    for u in auth_elem.findall('user'):
                        auth_elem.remove(u)

                if groups is not None:
                    for g in auth_elem.findall('group'):
                        auth_elem.remove(g)

        if auth_elem is None:
            # there is no sub-element 'auth' with the same type
            # (or no 'auth' at all); create it.
            auth_elem = E.auth(type=auth)
            access_elem.append(auth_elem)

        if users is not None:
            for u in users:
                auth_elem.append(E.user(u))

        if groups is not None:
            for g in groups:
                auth_elem.append(E.group(g))

        return access_elem
Ejemplo n.º 28
0
 def lookup(self, name):
     proxy_port = kconfig.get('display', 'display_proxy_port')
     return {'display_proxy_port': proxy_port,
             'version': get_version()}
Ejemplo n.º 29
0
 def config_lookup(self, name):
     return {'http_port': cherrypy.server.socket_port,
             'display_proxy_port':
             kconfig.get('display', 'display_proxy_port')}
Ejemplo n.º 30
0
 def __init__(self, **args):
     auth_type = config.get("authentication", "method")
     for klass in GroupsModel.__subclasses__():
         if auth_type == klass.auth_type:
             self.grp = klass(**args)
Ejemplo n.º 31
0
 def config_lookup(self, name):
     return {'http_port': cherrypy.config.nginx_port,
             'display_proxy_port':
             kconfig.get('display', 'display_proxy_port'),
             'version': config.get_version()}
Ejemplo n.º 32
0
 def __init__(self, **args):
     auth_type = config.get("authentication", "method")
     for klass in GroupsModel.__subclasses__():
         if auth_type == klass.auth_type:
             self.grp = klass(**args)
Ejemplo n.º 33
0
 def lookup(self, name):
     proxy_port = kconfig.get('display', 'display_proxy_port')
     return {'http_port': cherrypy.server.socket_port,
             'display_proxy_port': proxy_port}