diff options
author | Devaev Maxim <[email protected]> | 2019-04-09 07:13:13 +0300 |
---|---|---|
committer | Devaev Maxim <[email protected]> | 2019-04-09 07:13:13 +0300 |
commit | a6028c46a46fc06c8865679b8c922bfcd2852ab0 (patch) | |
tree | 106fde0b0f96f2ec3d27f6172c514791c619d306 /kvmd/apps | |
parent | 0460c2e83be9837fab01b116402d54c6b32ee4e4 (diff) |
auth plugins
Diffstat (limited to 'kvmd/apps')
-rw-r--r-- | kvmd/apps/__init__.py | 67 | ||||
-rw-r--r-- | kvmd/apps/htpasswd/__init__.py | 6 | ||||
-rw-r--r-- | kvmd/apps/kvmd/__init__.py | 15 | ||||
-rw-r--r-- | kvmd/apps/kvmd/auth.py | 56 | ||||
-rw-r--r-- | kvmd/apps/kvmd/server.py | 17 |
5 files changed, 105 insertions, 56 deletions
diff --git a/kvmd/apps/__init__.py b/kvmd/apps/__init__.py index 9a9a7593..77a9644b 100644 --- a/kvmd/apps/__init__.py +++ b/kvmd/apps/__init__.py @@ -35,6 +35,9 @@ import pygments import pygments.lexers.data import pygments.formatters +from ..plugins import UnknownPluginError +from ..plugins.auth import get_auth_service_class + from ..yamlconf import ConfigError from ..yamlconf import make_config from ..yamlconf import Section @@ -55,8 +58,6 @@ from ..validators.fs import valid_unix_mode from ..validators.net import valid_ip_or_host from ..validators.net import valid_port -from ..validators.auth import valid_auth_type - from ..validators.kvm import valid_stream_quality from ..validators.kvm import valid_stream_fps @@ -84,29 +85,11 @@ def init( args_parser.add_argument("-m", "--dump-config", dest="dump_config", action="store_true", help="View current configuration (include all overrides)") (options, remaining) = args_parser.parse_known_args(argv) - raw_config: Dict = {} - - if options.config_path: - options.config_path = os.path.expanduser(options.config_path) - raw_config = load_yaml_file(options.config_path) - - scheme = _get_config_scheme() - try: - _merge_dicts(raw_config, build_raw_from_options(options.set_options)) - config = make_config(raw_config, scheme) - except ConfigError as err: - raise SystemExit("Config error: " + str(err)) + config = _init_config(options.config_path, options.set_options) if options.dump_config: - dump = make_config_dump(config) - if sys.stdout.isatty(): - dump = pygments.highlight( - dump, - pygments.lexers.data.YamlLexer(), - pygments.formatters.TerminalFormatter(bg="dark"), # pylint: disable=no-member - ) - print(dump) - sys.exit(0) + _dump_config(config) + raise SystemExit() logging.captureWarnings(True) logging.config.dictConfig(config.logging) @@ -114,6 +97,35 @@ def init( # ===== +def _init_config(config_path: str, options: List[str]) -> Section: + config_path = os.path.expanduser(config_path) + raw_config: Dict = load_yaml_file(config_path) + + scheme = _get_config_scheme() + try: + _merge_dicts(raw_config, build_raw_from_options(options)) + config = make_config(raw_config, scheme) + + scheme["kvmd"]["auth"]["internal"] = get_auth_service_class(config.kvmd.auth.internal_type).get_options() + if config.kvmd.auth.external_type: + scheme["kvmd"]["auth"]["external"] = get_auth_service_class(config.kvmd.auth.external_type).get_options() + + return make_config(raw_config, scheme) + except (ConfigError, UnknownPluginError) as err: + raise SystemExit("Config error: %s" % (str(err))) + + +def _dump_config(config: Section) -> None: + dump = make_config_dump(config) + if sys.stdout.isatty(): + dump = pygments.highlight( + dump, + pygments.lexers.data.YamlLexer(), + pygments.formatters.TerminalFormatter(bg="dark"), # pylint: disable=no-member + ) + print(dump) + + def _merge_dicts(dest: Dict, src: Dict) -> None: for key in src: if key in dest: @@ -138,10 +150,11 @@ def _get_config_scheme() -> Dict: }, "auth": { - "type": Option("htpasswd", type=valid_auth_type, unpack_as="auth_type"), - "htpasswd": { - "file": Option("/etc/kvmd/htpasswd", type=valid_abs_path_exists, unpack_as="path"), - }, + "internal_users": Option([]), + "internal_type": Option("htpasswd"), + "external_type": Option(""), + # "internal": {}, + # "external": {}, }, "info": { diff --git a/kvmd/apps/htpasswd/__init__.py b/kvmd/apps/htpasswd/__init__.py index 486f00e4..a223fc16 100644 --- a/kvmd/apps/htpasswd/__init__.py +++ b/kvmd/apps/htpasswd/__init__.py @@ -44,9 +44,9 @@ from .. import init # ===== def _get_htpasswd_path(config: Section) -> str: - if config.kvmd.auth.type != "htpasswd": - print("Warning: KVMD does not use htpasswd auth", file=sys.stderr) - return config.kvmd.auth.htpasswd.file + if config.kvmd.auth.internal_type != "htpasswd": + raise SystemExit("Error: KVMD internal auth not using 'htpasswd' (now configured %r)" % (config.kvmd.auth.internal_type)) + return config.kvmd.auth.internal.file @contextlib.contextmanager diff --git a/kvmd/apps/kvmd/__init__.py b/kvmd/apps/kvmd/__init__.py index 1ab14fd6..9f849081 100644 --- a/kvmd/apps/kvmd/__init__.py +++ b/kvmd/apps/kvmd/__init__.py @@ -22,6 +22,9 @@ import asyncio +from typing import List +from typing import Optional + from ...logging import get_logger from ... import gpio @@ -39,13 +42,19 @@ from .server import Server # ===== -def main() -> None: - config = init("kvmd", description="The main Pi-KVM daemon")[2].kvmd +def main(argv: Optional[List[str]]=None) -> None: + config = init("kvmd", description="The main Pi-KVM daemon", argv=argv)[2].kvmd with gpio.bcm(): # pylint: disable=protected-access loop = asyncio.get_event_loop() Server( - auth_manager=AuthManager(**config.auth._unpack()), + auth_manager=AuthManager( + internal_users=config.auth.internal_users, + internal_type=config.auth.internal_type, + external_type=config.auth.external_type, + internal=config.auth.internal._unpack(), + external=(config.auth.external._unpack() if config.auth.external_type else {}), + ), info_manager=InfoManager(loop=loop, **config.info._unpack()), log_reader=LogReader(loop=loop), diff --git a/kvmd/apps/kvmd/auth.py b/kvmd/apps/kvmd/auth.py index 57b3bd54..c90f10b5 100644 --- a/kvmd/apps/kvmd/auth.py +++ b/kvmd/apps/kvmd/auth.py @@ -22,33 +22,56 @@ import secrets +from typing import List from typing import Dict from typing import Optional -import passlib.apache - from ...logging import get_logger +from ...plugins.auth import BaseAuthService +from ...plugins.auth import get_auth_service_class + # ===== class AuthManager: - def __init__(self, auth_type: str, htpasswd: Dict) -> None: - self.__login = { - "htpasswd": lambda: _HtpasswdLogin(**htpasswd), - }[auth_type]().login + def __init__( + self, + internal_users: List[str], + + internal_type: str, + external_type: str, + + internal: Dict, + external: Dict, + ) -> None: + + self.__internal_users = internal_users + self.__internal_service = get_auth_service_class(internal_type)(**internal) + get_logger().info("Using internal login service %r", self.__internal_service.PLUGIN_NAME) + + self.__external_service: Optional[BaseAuthService] = None + if external_type: + self.__external_service = get_auth_service_class(external_type)(**external) + get_logger().info("Using external login service %r", self.__external_service.PLUGIN_NAME) + self.__tokens: Dict[str, str] = {} # {token: user} - def login(self, user: str, passwd: str) -> Optional[str]: - if self.__login(user, passwd): + async def login(self, user: str, passwd: str) -> Optional[str]: + if user not in self.__internal_users and self.__external_service: + service = self.__external_service + else: + service = self.__internal_service + + if (await service.login(user, passwd)): for (token, token_user) in self.__tokens.items(): if user == token_user: return token token = secrets.token_hex(32) self.__tokens[token] = user - get_logger().info("Logged in user %r", user) + get_logger().info("Logged in user %r via login service %r", user, service.PLUGIN_NAME) return token else: - get_logger().error("Access denied for user %r", user) + get_logger().error("Access denied for user %r from login service %r", user, service.PLUGIN_NAME) return None def logout(self, token: str) -> None: @@ -59,12 +82,7 @@ class AuthManager: def check(self, token: str) -> Optional[str]: return self.__tokens.get(token) - -class _HtpasswdLogin: - def __init__(self, path: str) -> None: - get_logger().info("Using htpasswd auth file %r", path) - self.__path = path - - def login(self, user: str, passwd: str) -> bool: - htpasswd = passlib.apache.HtpasswdFile(self.__path) - return htpasswd.check_password(user, passwd) + async def cleanup(self) -> None: + await self.__internal_service.cleanup() + if self.__external_service: + await self.__external_service.cleanup() diff --git a/kvmd/apps/kvmd/server.py b/kvmd/apps/kvmd/server.py index 3a531484..97eb3310 100644 --- a/kvmd/apps/kvmd/server.py +++ b/kvmd/apps/kvmd/server.py @@ -311,7 +311,7 @@ class Server: # pylint: disable=too-many-instance-attributes @_exposed("POST", "/auth/login", auth_required=False) async def __auth_login_handler(self, request: aiohttp.web.Request) -> aiohttp.web.Response: credentials = await request.post() - token = self._auth_manager.login( + token = await self._auth_manager.login( user=valid_user(credentials.get("user", "")), passwd=valid_passwd(credentials.get("passwd", "")), ) @@ -533,9 +533,18 @@ class Server: # pylint: disable=too-many-instance-attributes await self.__remove_socket(ws) async def __on_cleanup(self, _: aiohttp.web.Application) -> None: - await self.__streamer.cleanup() - await self.__msd.cleanup() - await self.__hid.cleanup() + logger = get_logger(0) + for obj in [ + self._auth_manager, + self.__streamer, + self.__msd, + self.__hid, + ]: + logger.info("Cleaning up %s ...", type(obj).__name__) + try: + await obj.cleanup() # type: ignore + except Exception: + logger.exception("Cleanup error") async def __broadcast_event(self, event_type: _Events, event_attrs: Dict) -> None: if self.__sockets: |