CVoipAuthenticator/CVoipAuth.py
2025-06-22 18:16:01 +05:30

547 lines
20 KiB
Python

import sys
import Ice
import logging
import configparser
from threading import Timer
from optparse import OptionParser
from logging import debug, info, warning, error, critical, exception, getLogger
# === Configuration Helpers ===
def x2bool(s):
"""Convert config strings to boolean"""
if isinstance(s, bool):
return s
elif isinstance(s, str):
return s.lower() in ['1', 'true']
raise ValueError()
# === Default Configuration ===
cfgfile = 'CVoipAuth.ini'
default = {'django':(('enabled', x2bool, False),
('project', str, 'CVoipPanel'),
('settings', str, 'CVoipPanel.settings')),
'user':(('id_offset', int, 1000000000),
('avatar_enable', x2bool, False),
('reject_on_error', x2bool, True)),
'ice':(('host', str, '127.0.0.1'),
('port', int, 6502),
('slice', str, 'MumbleServer.ice'),
('secret', str, ''),
('watchdog', int, 30)),
'iceraw':None,
'murmur':(('servers', lambda x:list(map(int, x.split(','))), []),),
'glacier':(('enabled', x2bool, False),
('user', str, 'CVoipAuth'),
('password', str, 'secret'),
('host', str, 'localhost'),
('port', int, '4063')),
'log':(('level', int, logging.DEBUG),
('file', str, 'CVoipAuth.log'))}
# === Helper classes ===
class config(object):
def __init__(self, filename = None, default = None):
if not filename or not default: return
cfg = configparser.ConfigParser()
cfg.optionxform = str
cfg.read(filename)
for section, values in default.items():
if not values:
try:
self.__dict__[section] = cfg.items(section)
except configparser.NoSectionError:
self.__dict__[section] = []
else:
self.__dict__[section] = config()
for name, conv, vdefault in values:
try:
val = cfg.get(section, name)
self.__dict__[section].__dict__[name] = conv(val)
except (ValueError, configparser.NoSectionError, configparser.NoOptionError):
self.__dict__[section].__dict__[name] = vdefault
# === HTML Entity Handling ===
def entity_decode(string):
"""
Python reverse implementation of php htmlspecialchars
"""
htmlspecialchars = (('"', '"'),
("'", '''),
('<', '&lt;'),
('>', '&gt'),
('&', '&amp;'))
ret = string
for (s,t) in htmlspecialchars:
ret = ret.replace(t, s)
return ret
def entity_encode(string):
"""
Python implementation of htmlspecialchars
"""
htmlspecialchars = (('&', '&amp;'),
('"', '&quot;'),
("'", '&#039;'),
('<', '&lt;'),
('>', '&gt'))
ret = string
for (s,t) in htmlspecialchars:
ret = ret.replace(s, t)
return ret
# === Main Application ===
def do_main_program():
#
#--- Authenticator implementation
# All of this has to go in here so we can correctly daemonize the tool
# without loosing the file descriptors opened by the Ice module
slicedir = Ice.getSliceDir()
if not slicedir:
slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
else:
slicedir = ['-I' + slicedir]
Ice.loadSlice('', slicedir + [cfg.ice.slice])
import MumbleServer
class CVoipAuthenticatorApp(Ice.Application):
def run(self, args):
self.shutdownOnInterrupt()
if not self.initializeIceConnection():
return 1
if cfg.ice.watchdog > 0:
self.failedWatch = True
self.checkConnection()
self.communicator().waitForShutdown()
if hasattr(self, 'watchdog'):
self.watchdog.cancel()
if self.interrupted():
warning('Interrupt received - shutting down')
return 0
def initializeIceConnection(self):
ice = self.communicator()
if cfg.ice.secret:
ice.getImplicitContext().put("secret", cfg.ice.secret)
elif not cfg.glacier.enabled:
warning('No Ice secret configured - security risk')
info('Connecting to Ice at %s:%d', cfg.ice.host, cfg.ice.port)
proxy = ice.stringToProxy(f'Meta:tcp -h {cfg.ice.host} -p {cfg.ice.port}')
self.meta = MumbleServer.MetaPrx.uncheckedCast(proxy)
adapter = ice.createObjectAdapterWithEndpoints('Callback.Client', f'tcp -h {cfg.ice.host}')
adapter.activate()
self.metacb = MumbleServer.MetaCallbackPrx.uncheckedCast(
adapter.addWithUUID(metaCallback(self))
)
self.auth = MumbleServer.ServerUpdatingAuthenticatorPrx.uncheckedCast(
adapter.addWithUUID(CVoipAuthenticator())
)
return self.attachCallbacks()
def attachCallbacks(self, quiet=False):
try:
if not quiet:
info('Attaching meta callback')
self.meta.addCallback(self.metacb)
for server in self.meta.getBootedServers():
if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
if not quiet:
info('Configuring authenticator for server %d', server.id())
server.setAuthenticator(self.auth)
self.connected = True
return True
except (MumbleServer.InvalidSecretException, Ice.UnknownUserException) as e:
error('Connection failed: %s', str(e))
self.connected = False
return False
def checkConnection(self):
try:
self.attachCallbacks(quiet=not self.failedWatch)
self.failedWatch = False
except Ice.Exception as e:
error('Connection check failed: %s', str(e))
self.failedWatch = True
self.watchdog = Timer(cfg.ice.watchdog, self.checkConnection)
self.watchdog.start()
def checkSecret(func):
"""
Decorator that checks whether the server transmitted the right secret
if a secret is supposed to be used.
"""
if not cfg.ice.secret:
return func
def newfunc(*args, **kws):
if 'current' in kws:
current = kws["current"]
else:
current = args[-1]
if not current or 'secret' not in current.ctx or current.ctx['secret'] != cfg.ice.secret:
error('Server transmitted invalid secret. Possible injection attempt.')
raise MumbleServer.InvalidSecretException()
return func(*args, **kws)
return newfunc
def fortifyIceFu(retval = None, exceptions = (Ice.Exception,)):
"""
Decorator that catches exceptions,logs them and returns a safe retval
value. This helps preventing the authenticator getting stuck in
critical code paths. Only exceptions that are instances of classes
given in the exceptions list are not caught.
The default is to catch all non-Ice exceptions.
"""
def newdec(func):
def newfunc(*args, **kws):
try:
return func(*args, **kws)
except Exception as e:
catch = True
for ex in exceptions:
if isinstance(e, ex):
catch = False
break
if catch:
critical('Unexpected exception caught')
exception(e)
return retval
raise
return newfunc
return newdec
class metaCallback(MumbleServer.MetaCallback):
def __init__(self, app):
MumbleServer.MetaCallback.__init__(self)
self.app = app
@fortifyIceFu()
@checkSecret
def started(self, server, current = None):
"""
This function is called when a virtual server is started
and makes sure an authenticator gets attached if needed.
"""
if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
info('Setting authenticator for virtual server %d', server.id())
try:
server.setAuthenticator(app.auth)
# Apparently this server was restarted without us noticing
except (MumbleServer.InvalidSecretException, Ice.UnknownUserException) as e:
if hasattr(e, "unknown") and e.unknown != "MumbleServer::InvalidSecretException":
# Special handling for Murmur 1.2.2 servers with invalid slice files
raise e
error('Invalid ice secret')
return
else:
debug('Virtual server %d got started', server.id())
@fortifyIceFu()
@checkSecret
def stopped(self, server, current = None):
"""
This function is called when a virtual server is stopped
"""
if self.app.connected:
# Only try to output the server id if we think we are still connected to prevent
# flooding of our thread pool
try:
if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
info('Authenticated virtual server %d got stopped', server.id())
else:
debug('Virtual server %d got stopped', server.id())
return
except Ice.ConnectionRefusedException:
self.app.connected = False
debug('Server shutdown stopped a virtual server')
if cfg.user.reject_on_error: # Python 2.4 compat
authenticateFortifyResult = (-1, None, None)
else:
authenticateFortifyResult = (-2, None, None)
class CVoipAuthenticator(MumbleServer.ServerUpdatingAuthenticator):
texture_cache = {}
def __init__(self):
MumbleServer.ServerUpdatingAuthenticator.__init__(self)
@fortifyIceFu(authenticateFortifyResult)
@checkSecret
def authenticate(self, name, pw, certlist, certhash, strong, current = None):
FALL_THROUGH = -2
AUTH_REFUSED = -1
# Django authenticator
if cfg.django.enabled:
import os
import django
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), cfg.django.project))
sys.path.append(BASE_DIR)
info('Using Django project from %s', BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", cfg.django.settings)
django.setup()
from django.contrib.auth.models import User
debug('Using Django for authentication')
try:
user = User.objects.get(username=name)
debug('User found: %s', user.username)
if user.check_password(pw) and pw not in ('', None):
# Successful authentication
uid = user.id + cfg.user.id_offset
groups = [group.name for group in user.groups.all()]
info('User authenticated: "%s" (%d)', name, uid)
return (uid, entity_decode(user.get_full_name()), groups)
else:
info('Failed authentication attempt for user: "%s" (%d)', name, user.id + cfg.user.id_offset)
return (AUTH_REFUSED, None, None)
except User.DoesNotExist:
info('Refuse Connection for unknown user "%s"', name)
return (AUTH_REFUSED, None, None)
info('Failed authentication attempt for user: "%s"', name)
return (AUTH_REFUSED, None, None)
@fortifyIceFu((False, None))
@checkSecret
def getInfo(self, id, current = None):
"""
Gets called to fetch user specific information
"""
# We do not expose any additional information so always fall through
debug('getInfo for %d -> denied', id)
return (False, None)
@fortifyIceFu(-2)
@checkSecret
def nameToId(self, name, current = None):
"""
Gets called to get the id for a given username
"""
FALL_THROUGH = -2
if name == 'SuperUser':
debug('nameToId SuperUser -> forced fall through')
return FALL_THROUGH
@fortifyIceFu("")
@checkSecret
def idToName(self, id, current = None):
"""
Gets called to get the username for a given id
"""
FALL_THROUGH = ""
# Make sure the ID is in our range and transform it to the actual smf user id
if id < cfg.user.id_offset:
return FALL_THROUGH
bbid = id - cfg.user.id_offset
debug('idToName %d -> ?', id)
return FALL_THROUGH
@fortifyIceFu("")
@checkSecret
def idToTexture(self, id, current = None):
"""
Gets called to get the corresponding texture for a user
"""
FALL_THROUGH = ""
debug('idToTexture for %d', id)
if id < cfg.user.id_offset or not cfg.user.avatar_enable:
debug('idToTexture %d -> fall through', id)
return FALL_THROUGH
@fortifyIceFu(-2)
@checkSecret
def registerUser(self, name, current = None):
"""
Gets called when the server is asked to register a user.
"""
FALL_THROUGH = -2
debug('registerUser "%s" -> fall through', name)
return FALL_THROUGH
@fortifyIceFu(-1)
@checkSecret
def unregisterUser(self, id, current = None):
"""
Gets called when the server is asked to unregister a user.
"""
FALL_THROUGH = -1
# Return -1 to fall through to internal server database, we will not modify the smf database
# but we can make murmur delete all additional information it got this way.
debug('unregisterUser %d -> fall through', id)
return FALL_THROUGH
@fortifyIceFu(-1)
@checkSecret
def setInfo(self, id, info, current = None):
"""
Gets called when the server is supposed to save additional information
about a user to his database
"""
FALL_THROUGH = -1
# Return -1 to fall through to the internal server handler. We must not modify
# the smf database so the additional information is stored in murmurs database
debug('setInfo %d -> fall through', id)
return FALL_THROUGH
@fortifyIceFu(-1)
@checkSecret
def setTexture(self, id, texture, current = None):
"""
Gets called when the server is asked to update the user texture of a user
"""
FAILED = 0
FALL_THROUGH = -1
if id < cfg.user.id_offset:
debug('setTexture %d -> fall through', id)
return FALL_THROUGH
if cfg.user.avatar_enable:
# Report a fail (0) as we will not update the avatar in the smf database.
debug('setTexture %d -> failed', id)
return FAILED
# If we don't use textures from smf we let mumble save it
debug('setTexture %d -> fall through', id)
return FALL_THROUGH
class CustomLogger(Ice.Logger):
"""
Logger implementation to pipe Ice log messages into
our own log
"""
def __init__(self):
Ice.Logger.__init__(self)
self._log = getLogger('Ice')
def _print(self, message):
self._log.info(message)
def trace(self, category, message):
self._log.debug('Trace %s: %s', category, message)
def warning(self, message):
self._log.warning(message)
def error(self, message):
self._log.error(message)
# === Start of authenticator ===
info('Starting cvoip authenticator')
initdata = Ice.InitializationData()
initdata.properties = Ice.createProperties([], initdata.properties)
for prop, val in cfg.iceraw:
initdata.properties.setProperty(prop, val)
initdata.properties.setProperty('Ice.ImplicitContext', 'Shared')
initdata.properties.setProperty('Ice.Default.EncodingVersion', '1.0')
initdata.logger = CustomLogger()
app = CVoipAuthenticatorApp()
state = app.main(sys.argv[:1], initData = initdata)
info('Shutdown complete')
# === Entry Point ===
if __name__ == '__main__':
# Parse commandline options
parser = OptionParser()
parser.add_option('-i', '--ini',
help = 'load configuration from INI', default = cfgfile)
parser.add_option('-v', '--verbose', action='store_true', dest = 'verbose',
help = 'verbose output [default]', default = True)
parser.add_option('-q', '--quiet', action='store_false', dest = 'verbose',
help = 'only error output')
parser.add_option('-l', '--logfile', action='store_true', dest = 'logfile',
help = 'log output to file instead of terminal', default = False)
parser.add_option('-d', '--daemon', action='store_true', dest = 'force_daemon',
help = 'run as daemon', default = False)
parser.add_option('-a', '--app', action='store_true', dest = 'force_app',
help = 'do not run as daemon', default = False)
(option, args) = parser.parse_args()
if option.force_daemon and option.force_app:
parser.print_help()
sys.exit(1)
# Load configuration
try:
cfg = config(option.ini, default)
except Exception as e:
print('Fatal error, could not load config file from "%s"' % cfgfile, file=sys.stderr)
sys.exit(1)
# Initialize logger
if cfg.log.file and option.logfile:
try:
logfile = open(cfg.log.file, 'a')
except IOError as e:
#print>>sys.stderr, str(e)
print('Fatal error, could not open logfile "%s"' % cfg.log.file, file=sys.stderr)
sys.exit(1)
else:
logfile = logging.sys.stderr
if option.verbose:
level = cfg.log.level
else:
level = logging.ERROR
logging.basicConfig(level = level,
format='%(asctime)s %(levelname)s %(message)s',
stream = logfile if option.logfile else sys.stdout)
# By default, we'll run it as an app.
# Upgrade to run as a daemon if the user explicitly defined the option with the -a / -d parameter.
try:
if option.force_daemon:
import daemon
else:
raise ImportError # Pretend that we don't have the daemon library
except ImportError:
if option.force_daemon:
print('Fatal error, could not daemonize process due to missing "daemon" library, ' \
'please install the missing dependency and restart the authenticator', file=sys.stderr)
sys.exit(1)
do_main_program()
else:
context = daemon.DaemonContext(working_directory = sys.path[0],
stderr = logfile)
context.__enter__()
try:
do_main_program()
finally:
context.__exit__(None, None, None)