85
82
SO_BINDTODEVICE = None
89
stored_state_path = "/var/lib/mandos/clients.pickle"
91
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
address = str("/dev/log")))
96
def initlogger(level=logging.WARNING):
97
"""init logger and add loglevel"""
99
syslogger.setFormatter(logging.Formatter
100
('Mandos [%(process)d]: %(levelname)s:'
102
logger.addHandler(syslogger)
104
console = logging.StreamHandler()
105
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
109
logger.addHandler(console)
110
logger.setLevel(level)
92
syslogger.setFormatter(logging.Formatter
93
('Mandos [%(process)d]: %(levelname)s:'
95
logger.addHandler(syslogger)
97
console = logging.StreamHandler()
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
101
logger.addHandler(console)
113
103
class AvahiError(Exception):
114
104
def __init__(self, value, *args, **kwargs):
333
313
"created", "enabled", "fingerprint",
334
314
"host", "interval", "last_checked_ok",
335
315
"last_enabled", "name", "timeout")
337
317
def timeout_milliseconds(self):
338
318
"Return the 'timeout' attribute in milliseconds"
339
319
return _timedelta_to_milliseconds(self.timeout)
341
321
def extended_timeout_milliseconds(self):
342
322
"Return the 'extended_timeout' attribute in milliseconds"
343
return _timedelta_to_milliseconds(self.extended_timeout)
323
return _timedelta_to_milliseconds(self.extended_timeout)
345
325
def interval_milliseconds(self):
346
326
"Return the 'interval' attribute in milliseconds"
347
327
return _timedelta_to_milliseconds(self.interval)
349
329
def approval_delay_milliseconds(self):
350
330
return _timedelta_to_milliseconds(self.approval_delay)
352
def __init__(self, name = None, config=None):
332
def __init__(self, name = None, disable_hook=None, config=None):
353
333
"""Note: the 'checker' key in 'config' sets the
354
334
'checker_command' attribute and *not* the 'checker'
376
356
self.host = config.get("host", "")
377
357
self.created = datetime.datetime.utcnow()
379
359
self.last_approval_request = None
380
self.last_enabled = datetime.datetime.utcnow()
360
self.last_enabled = None
381
361
self.last_checked_ok = None
382
self.last_checker_status = None
383
362
self.timeout = string_to_delta(config["timeout"])
384
self.extended_timeout = string_to_delta(config
385
["extended_timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
386
364
self.interval = string_to_delta(config["interval"])
365
self.disable_hook = disable_hook
387
366
self.checker = None
388
367
self.checker_initiator_tag = None
389
368
self.disable_initiator_tag = None
390
self.expires = datetime.datetime.utcnow() + self.timeout
391
370
self.checker_callback_tag = None
392
371
self.checker_command = config["checker"]
393
372
self.current_checker_command = None
373
self.last_connect = None
394
374
self._approved = None
395
375
self.approved_by_default = config.get("approved_by_default",
399
379
config["approval_delay"])
400
380
self.approval_duration = string_to_delta(
401
381
config["approval_duration"])
402
self.changedstate = (multiprocessing_manager
403
.Condition(multiprocessing_manager
405
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
406
self.client_structure.append("client_structure")
409
for name, t in inspect.getmembers(type(self),
410
lambda obj: isinstance(obj, property)):
411
if not name.startswith("_"):
412
self.client_structure.append(name)
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
414
# Send notice to process children that client state has changed
415
384
def send_changedstate(self):
416
with self.changedstate:
417
self.changedstate.notify_all()
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
419
389
def enable(self):
420
390
"""Start this client's checker and timeout hooks"""
421
391
if getattr(self, "enabled", False):
422
392
# Already enabled
424
394
self.send_changedstate()
395
# Schedule a new checker to be started an 'interval' from now,
396
# and every interval from then on.
397
self.checker_initiator_tag = (gobject.timeout_add
398
(self.interval_milliseconds(),
400
# Schedule a disable() when 'timeout' has passed
425
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
self.disable_initiator_tag = (gobject.timeout_add
403
(self.timeout_milliseconds(),
426
405
self.enabled = True
427
406
self.last_enabled = datetime.datetime.utcnow()
407
# Also start a new checker *right now*.
430
410
def disable(self, quiet=True):
431
411
"""Disable this client."""
443
423
gobject.source_remove(self.checker_initiator_tag)
444
424
self.checker_initiator_tag = None
445
425
self.stop_checker()
426
if self.disable_hook:
427
self.disable_hook(self)
446
428
self.enabled = False
447
429
# Do not run this again if called by a gobject.timeout_add
450
432
def __del__(self):
433
self.disable_hook = None
453
def init_checker(self):
454
# Schedule a new checker to be started an 'interval' from now,
455
# and every interval from then on.
456
self.checker_initiator_tag = (gobject.timeout_add
457
(self.interval_milliseconds(),
459
# Schedule a disable() when 'timeout' has passed
460
self.disable_initiator_tag = (gobject.timeout_add
461
(self.timeout_milliseconds(),
463
# Also start a new checker *right now*.
467
436
def checker_callback(self, pid, condition, command):
468
437
"""The checker has completed, so take appropriate actions."""
469
438
self.checker_callback_tag = None
470
439
self.checker = None
471
440
if os.WIFEXITED(condition):
472
self.last_checker_status = os.WEXITSTATUS(condition)
473
if self.last_checker_status == 0:
441
exitstatus = os.WEXITSTATUS(condition)
474
443
logger.info("Checker for %(name)s succeeded",
476
445
self.checked_ok()
491
459
if timeout is None:
492
460
timeout = self.timeout
493
461
self.last_checked_ok = datetime.datetime.utcnow()
494
if self.disable_initiator_tag is not None:
495
gobject.source_remove(self.disable_initiator_tag)
496
if getattr(self, "enabled", False):
497
self.disable_initiator_tag = (gobject.timeout_add
498
(_timedelta_to_milliseconds
499
(timeout), self.disable))
500
self.expires = datetime.datetime.utcnow() + timeout
462
gobject.source_remove(self.disable_initiator_tag)
463
self.expires = datetime.datetime.utcnow() + timeout
464
self.disable_initiator_tag = (gobject.timeout_add
465
(_timedelta_to_milliseconds(timeout),
502
468
def need_approval(self):
503
469
self.last_approval_request = datetime.datetime.utcnow()
596
562
self.checker = None
598
# Encrypts a client secret and stores it in a varible encrypted_secret
599
def encrypt_secret(self, key):
600
# Encryption-key need to be of a specific size, so we hash inputed key
601
hasheng = hashlib.sha256()
603
encryptionkey = hasheng.digest()
605
# Create validation hash so we know at decryption if it was sucessful
606
hasheng = hashlib.sha256()
607
hasheng.update(self.secret)
608
validationhash = hasheng.digest()
611
iv = os.urandom(Crypto.Cipher.AES.block_size)
612
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
613
Crypto.Cipher.AES.MODE_CFB, iv)
614
ciphertext = ciphereng.encrypt(validationhash+self.secret)
615
self.encrypted_secret = (ciphertext, iv)
617
# Decrypt a encrypted client secret
618
def decrypt_secret(self, key):
619
# Decryption-key need to be of a specific size, so we hash inputed key
620
hasheng = hashlib.sha256()
622
encryptionkey = hasheng.digest()
624
# Decrypt encrypted secret
625
ciphertext, iv = self.encrypted_secret
626
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
627
Crypto.Cipher.AES.MODE_CFB, iv)
628
plain = ciphereng.decrypt(ciphertext)
630
# Validate decrypted secret to know if it was succesful
631
hasheng = hashlib.sha256()
632
validationhash = plain[:hasheng.digest_size]
633
secret = plain[hasheng.digest_size:]
634
hasheng.update(secret)
636
# if validation fails, we use key as new secret. Otherwhise, we use
637
# the decrypted secret
638
if hasheng.digest() == validationhash:
642
del self.encrypted_secret
645
564
def dbus_service_property(dbus_interface, signature="v",
646
565
access="readwrite", byte_arrays=False):
647
566
"""Decorators for marking methods of a DBusObjectWithProperties to
706
625
def _get_all_dbus_properties(self):
707
626
"""Returns a generator of (name, attribute) pairs
709
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
710
for cls in self.__class__.__mro__
628
return ((prop._dbus_name, prop)
711
629
for name, prop in
712
inspect.getmembers(cls, self._is_dbus_property))
630
inspect.getmembers(self, self._is_dbus_property))
714
632
def _get_dbus_property(self, interface_name, property_name):
715
633
"""Returns a bound method if one exists which is a D-Bus
716
634
property with the specified name and interface.
718
for cls in self.__class__.__mro__:
719
for name, value in (inspect.getmembers
720
(cls, self._is_dbus_property)):
721
if (value._dbus_name == property_name
722
and value._dbus_interface == interface_name):
723
return value.__get__(self)
636
for name in (property_name,
637
property_name + "_dbus_property"):
638
prop = getattr(self, name, None)
640
or not self._is_dbus_property(prop)
641
or prop._dbus_name != property_name
642
or (interface_name and prop._dbus_interface
643
and interface_name != prop._dbus_interface)):
725
646
# No such property
726
647
raise DBusPropertyNotFound(self.dbus_object_path + ":"
727
648
+ interface_name + "."
836
757
return dbus.String(dt.isoformat(),
837
758
variant_level=variant_level)
839
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
841
"""Applied to an empty subclass of a D-Bus object, this metaclass
842
will add additional D-Bus attributes matching a certain pattern.
844
def __new__(mcs, name, bases, attr):
845
# Go through all the base classes which could have D-Bus
846
# methods, signals, or properties in them
847
for base in (b for b in bases
848
if issubclass(b, dbus.service.Object)):
849
# Go though all attributes of the base class
850
for attrname, attribute in inspect.getmembers(base):
851
# Ignore non-D-Bus attributes, and D-Bus attributes
852
# with the wrong interface name
853
if (not hasattr(attribute, "_dbus_interface")
854
or not attribute._dbus_interface
855
.startswith("se.recompile.Mandos")):
857
# Create an alternate D-Bus interface name based on
859
alt_interface = (attribute._dbus_interface
860
.replace("se.recompile.Mandos",
861
"se.bsnet.fukt.Mandos"))
862
# Is this a D-Bus signal?
863
if getattr(attribute, "_dbus_is_signal", False):
864
# Extract the original non-method function by
866
nonmethod_func = (dict(
867
zip(attribute.func_code.co_freevars,
868
attribute.__closure__))["func"]
870
# Create a new, but exactly alike, function
871
# object, and decorate it to be a new D-Bus signal
872
# with the alternate D-Bus interface name
873
new_function = (dbus.service.signal
875
attribute._dbus_signature)
877
nonmethod_func.func_code,
878
nonmethod_func.func_globals,
879
nonmethod_func.func_name,
880
nonmethod_func.func_defaults,
881
nonmethod_func.func_closure)))
882
# Define a creator of a function to call both the
883
# old and new functions, so both the old and new
884
# signals gets sent when the function is called
885
def fixscope(func1, func2):
886
"""This function is a scope container to pass
887
func1 and func2 to the "call_both" function
888
outside of its arguments"""
889
def call_both(*args, **kwargs):
890
"""This function will emit two D-Bus
891
signals by calling func1 and func2"""
892
func1(*args, **kwargs)
893
func2(*args, **kwargs)
895
# Create the "call_both" function and add it to
897
attr[attrname] = fixscope(attribute,
899
# Is this a D-Bus method?
900
elif getattr(attribute, "_dbus_is_method", False):
901
# Create a new, but exactly alike, function
902
# object. Decorate it to be a new D-Bus method
903
# with the alternate D-Bus interface name. Add it
905
attr[attrname] = (dbus.service.method
907
attribute._dbus_in_signature,
908
attribute._dbus_out_signature)
910
(attribute.func_code,
911
attribute.func_globals,
913
attribute.func_defaults,
914
attribute.func_closure)))
915
# Is this a D-Bus property?
916
elif getattr(attribute, "_dbus_is_property", False):
917
# Create a new, but exactly alike, function
918
# object, and decorate it to be a new D-Bus
919
# property with the alternate D-Bus interface
920
# name. Add it to the class.
921
attr[attrname] = (dbus_service_property
923
attribute._dbus_signature,
924
attribute._dbus_access,
926
._dbus_get_args_options
929
(attribute.func_code,
930
attribute.func_globals,
932
attribute.func_defaults,
933
attribute.func_closure)))
934
return type.__new__(mcs, name, bases, attr)
936
760
class ClientDBus(Client, DBusObjectWithProperties):
937
761
"""A Client class using D-Bus
964
787
def notifychangeproperty(transform_func,
965
788
dbus_name, type_func=lambda x: x,
966
789
variant_level=1):
967
""" Modify a variable so that it's a property which announces
970
transform_fun: Function that takes a value and a variant_level
971
and transforms it to a D-Bus type.
972
dbus_name: D-Bus name of the variable
790
""" Modify a variable so that its a property that announce its
792
transform_fun: Function that takes a value and transform it to
794
dbus_name: DBus name of the variable
973
795
type_func: Function that transform the value before sending it
974
to the D-Bus. Default: no transform
975
variant_level: D-Bus variant level. Default: 1
797
variant_level: DBus variant level. default: 1
977
attrname = "_{0}".format(dbus_name)
978
800
def setter(self, value):
801
old_value = real_value[0]
802
real_value[0] = value
979
803
if hasattr(self, "dbus_object_path"):
980
if (not hasattr(self, attrname) or
981
type_func(getattr(self, attrname, None))
982
!= type_func(value)):
983
dbus_value = transform_func(type_func(value),
804
if type_func(old_value) != type_func(real_value[0]):
805
dbus_value = transform_func(type_func(real_value[0]),
986
807
self.PropertyChanged(dbus.String(dbus_name),
988
setattr(self, attrname, value)
990
return property(lambda self: getattr(self, attrname), setter)
810
return property(lambda self: real_value[0], setter)
993
813
expires = notifychangeproperty(datetime_to_dbus, "Expires")
994
814
approvals_pending = notifychangeproperty(dbus.Boolean,
995
815
"ApprovalPending",
998
818
last_enabled = notifychangeproperty(datetime_to_dbus,
1000
820
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1001
type_func = lambda checker:
1002
checker is not None)
821
type_func = lambda checker: checker is not None)
1003
822
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1004
823
"LastCheckedOK")
1005
last_approval_request = notifychangeproperty(
1006
datetime_to_dbus, "LastApprovalRequest")
824
last_approval_request = notifychangeproperty(datetime_to_dbus,
825
"LastApprovalRequest")
1007
826
approved_by_default = notifychangeproperty(dbus.Boolean,
1008
827
"ApprovedByDefault")
1009
approval_delay = notifychangeproperty(dbus.UInt16,
1012
_timedelta_to_milliseconds)
1013
approval_duration = notifychangeproperty(
1014
dbus.UInt16, "ApprovalDuration",
1015
type_func = _timedelta_to_milliseconds)
828
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
829
type_func = _timedelta_to_milliseconds)
830
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
831
type_func = _timedelta_to_milliseconds)
1016
832
host = notifychangeproperty(dbus.String, "Host")
1017
833
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1019
_timedelta_to_milliseconds)
1020
extended_timeout = notifychangeproperty(
1021
dbus.UInt16, "ExtendedTimeout",
1022
type_func = _timedelta_to_milliseconds)
1023
interval = notifychangeproperty(dbus.UInt16,
1026
_timedelta_to_milliseconds)
834
type_func = _timedelta_to_milliseconds)
835
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
836
type_func = _timedelta_to_milliseconds)
837
interval = notifychangeproperty(dbus.UInt16, "Interval",
838
type_func = _timedelta_to_milliseconds)
1027
839
checker_command = notifychangeproperty(dbus.String, "Checker")
1029
841
del notifychangeproperty
1383
1185
unicode(self.client_address))
1384
1186
logger.debug("Pipe FD: %d",
1385
1187
self.server.child_pipe.fileno())
1387
1189
session = (gnutls.connection
1388
1190
.ClientSession(self.request,
1389
1191
gnutls.connection
1390
1192
.X509Credentials()))
1392
1194
# Note: gnutls.connection.X509Credentials is really a
1393
1195
# generic GnuTLS certificate credentials object so long as
1394
1196
# no X.509 keys are added to it. Therefore, we can use it
1395
1197
# here despite using OpenPGP certificates.
1397
1199
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1398
1200
# "+AES-256-CBC", "+SHA1",
1399
1201
# "+COMP-NULL", "+CTYPE-OPENPGP",
1619
1413
This function creates a new pipe in self.pipe
1621
1415
parent_pipe, self.child_pipe = multiprocessing.Pipe()
1623
proc = MultiprocessingMixIn.process_request(self, request,
1417
super(MultiprocessingMixInWithPipe,
1418
self).process_request(request, client_address)
1625
1419
self.child_pipe.close()
1626
self.add_pipe(parent_pipe, proc)
1628
def add_pipe(self, parent_pipe, proc):
1420
self.add_pipe(parent_pipe)
1422
def add_pipe(self, parent_pipe):
1629
1423
"""Dummy function; override as necessary"""
1630
1424
raise NotImplementedError
1633
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1634
1427
socketserver.TCPServer, object):
1635
1428
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
1719
1512
def server_activate(self):
1720
1513
if self.enabled:
1721
1514
return socketserver.TCPServer.server_activate(self)
1723
1515
def enable(self):
1724
1516
self.enabled = True
1726
def add_pipe(self, parent_pipe, proc):
1517
def add_pipe(self, parent_pipe):
1727
1518
# Call "handle_ipc" for both data and EOF events
1728
1519
gobject.io_add_watch(parent_pipe.fileno(),
1729
1520
gobject.IO_IN | gobject.IO_HUP,
1730
1521
functools.partial(self.handle_ipc,
1522
parent_pipe = parent_pipe))
1735
1524
def handle_ipc(self, source, condition, parent_pipe=None,
1736
proc = None, client_object=None):
1525
client_object=None):
1737
1526
condition_names = {
1738
1527
gobject.IO_IN: "IN", # There is data to read.
1739
1528
gobject.IO_OUT: "OUT", # Data can be written (without
1771
1558
"dress: %s", fpr, address)
1772
1559
if self.use_dbus:
1773
1560
# Emit D-Bus signal
1774
mandos_dbus_service.ClientNotFound(fpr,
1561
mandos_dbus_service.ClientNotFound(fpr, address[0])
1776
1562
parent_pipe.send(False)
1779
1565
gobject.io_add_watch(parent_pipe.fileno(),
1780
1566
gobject.IO_IN | gobject.IO_HUP,
1781
1567
functools.partial(self.handle_ipc,
1568
parent_pipe = parent_pipe,
1569
client_object = client))
1787
1570
parent_pipe.send(True)
1788
# remove the old hook in favor of the new above hook on
1571
# remove the old hook in favor of the new above hook on same fileno
1791
1573
if command == 'funcall':
1792
1574
funcname = request[1]
1793
1575
args = request[2]
1794
1576
kwargs = request[3]
1796
parent_pipe.send(('data', getattr(client_object,
1578
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1800
1580
if command == 'getattr':
1801
1581
attrname = request[1]
1802
1582
if callable(client_object.__getattribute__(attrname)):
1803
1583
parent_pipe.send(('function',))
1805
parent_pipe.send(('data', client_object
1806
.__getattribute__(attrname)))
1585
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1808
1587
if command == 'setattr':
1809
1588
attrname = request[1]
1810
1589
value = request[2]
1811
1590
setattr(client_object, attrname, value)
2103
1877
# End of Avahi example code
2106
bus_name = dbus.service.BusName("se.recompile.Mandos",
1880
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2107
1881
bus, do_not_queue=True)
2108
old_bus_name = (dbus.service.BusName
2109
("se.bsnet.fukt.Mandos", bus,
2111
1882
except dbus.exceptions.NameExistsException as e:
2112
1883
logger.error(unicode(e) + ", disabling D-Bus")
2113
1884
use_dbus = False
2114
1885
server_settings["use_dbus"] = False
2115
1886
tcp_server.use_dbus = False
2116
1887
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2117
service = AvahiServiceToSyslog(name =
2118
server_settings["servicename"],
2119
servicetype = "_mandos._tcp",
2120
protocol = protocol, bus = bus)
1888
service = AvahiService(name = server_settings["servicename"],
1889
servicetype = "_mandos._tcp",
1890
protocol = protocol, bus = bus)
2121
1891
if server_settings["interface"]:
2122
1892
service.interface = (if_nametoindex
2123
1893
(str(server_settings["interface"])))
2128
1898
client_class = Client
2130
client_class = functools.partial(ClientDBusTransitional,
2133
special_settings = {
2134
# Some settings need to be accessd by special methods;
2135
# booleans need .getboolean(), etc. Here is a list of them:
2136
"approved_by_default":
2138
client_config.getboolean(section, "approved_by_default"),
2140
# Construct a new dict of client settings of this form:
2141
# { client_name: {setting_name: value, ...}, ...}
2142
# with exceptions for any special settings as defined above
2143
client_settings = dict((clientname,
2145
(value if setting not in special_settings
2146
else special_settings[setting](clientname)))
2147
for setting, value in client_config.items(clientname)))
2148
for clientname in client_config.sections())
2150
old_client_settings = {}
2153
# Get client data and settings from last running state.
2154
if server_settings["restore"]:
2156
with open(stored_state_path, "rb") as stored_state:
2157
clients_data, old_client_settings = pickle.load(stored_state)
2158
os.remove(stored_state_path)
2159
except IOError as e:
2160
logger.warning("Could not load persistant state: {0}".format(e))
2161
if e.errno != errno.ENOENT:
2164
for client in clients_data:
2165
client_name = client["name"]
2167
# Decide which value to use after restoring saved state.
2168
# We have three different values: Old config file,
2169
# new config file, and saved state.
2170
# New config value takes precedence if it differs from old
2171
# config value, otherwise use saved state.
2172
for name, value in client_settings[client_name].items():
1900
client_class = functools.partial(ClientDBus, bus = bus)
1901
def client_config_items(config, section):
1902
special_settings = {
1903
"approved_by_default":
1904
lambda: config.getboolean(section,
1905
"approved_by_default"),
1907
for name, value in config.items(section):
2174
# For each value in new config, check if it differs
2175
# from the old config value (Except for the "secret"
2177
if name != "secret" and value != old_client_settings[client_name][name]:
2178
setattr(client, name, value)
1909
yield (name, special_settings[name]())
2179
1910
except KeyError:
2182
# Clients who has passed its expire date, can still be enabled if its
2183
# last checker was sucessful. Clients who checkers failed before we
2184
# stored it state is asumed to had failed checker during downtime.
2185
if client["enabled"] and client["last_checked_ok"]:
2186
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2187
> client["interval"]):
2188
if client["last_checker_status"] != 0:
2189
client["enabled"] = False
2191
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2193
client["changedstate"] = (multiprocessing_manager
2194
.Condition(multiprocessing_manager
2197
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2198
tcp_server.clients[client_name] = new_client
2199
new_client.bus = bus
2200
for name, value in client.iteritems():
2201
setattr(new_client, name, value)
2202
client_object_name = unicode(client_name).translate(
2203
{ord("."): ord("_"),
2204
ord("-"): ord("_")})
2205
new_client.dbus_object_path = (dbus.ObjectPath
2206
("/clients/" + client_object_name))
2207
DBusObjectWithProperties.__init__(new_client,
2209
new_client.dbus_object_path)
2211
tcp_server.clients[client_name] = Client.__new__(Client)
2212
for name, value in client.iteritems():
2213
setattr(tcp_server.clients[client_name], name, value)
2215
tcp_server.clients[client_name].decrypt_secret(
2216
client_settings[client_name]["secret"])
2218
# Create/remove clients based on new changes made to config
2219
for clientname in set(old_client_settings) - set(client_settings):
2220
del tcp_server.clients[clientname]
2221
for clientname in set(client_settings) - set(old_client_settings):
2222
tcp_server.clients[clientname] = (client_class(name = clientname,
1913
tcp_server.clients.update(set(
1914
client_class(name = section,
1915
config= dict(client_config_items(
1916
client_config, section)))
1917
for section in client_config.sections()))
2228
1918
if not tcp_server.clients:
2229
1919
logger.warning("No clients defined")
2304
class MandosDBusServiceTransitional(MandosDBusService):
2305
__metaclass__ = AlternateDBusNamesMetaclass
2306
mandos_dbus_service = MandosDBusServiceTransitional()
1993
mandos_dbus_service = MandosDBusService()
2309
1996
"Cleanup function; run on exit"
2310
1997
service.cleanup()
2312
multiprocessing.active_children()
2313
if not (tcp_server.clients or client_settings):
2316
# Store client before exiting. Secrets are encrypted with key based
2317
# on what config file has. If config file is removed/edited, old
2318
# secret will thus be unrecovable.
2320
for client in tcp_server.clients.itervalues():
2321
client.encrypt_secret(client_settings[client.name]["secret"])
2325
# A list of attributes that will not be stored when shuting down.
2326
exclude = set(("bus", "changedstate", "secret"))
2327
for name, typ in inspect.getmembers(dbus.service.Object):
2330
client_dict["encrypted_secret"] = client.encrypted_secret
2331
for attr in client.client_structure:
2332
if attr not in exclude:
2333
client_dict[attr] = getattr(client, attr)
2335
clients.append(client_dict)
2336
del client_settings[client.name]["secret"]
2339
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2340
pickle.dump((clients, client_settings), stored_state)
2341
except IOError as e:
2342
logger.warning("Could not save persistant state: {0}".format(e))
2343
if e.errno != errno.ENOENT:
2346
# Delete all clients, and settings from config
2347
1999
while tcp_server.clients:
2348
name, client = tcp_server.clients.popitem()
2000
client = tcp_server.clients.pop()
2350
2002
client.remove_from_connection()
2003
client.disable_hook = None
2351
2004
# Don't signal anything except ClientRemoved
2352
2005
client.disable(quiet=True)
2354
2007
# Emit D-Bus signal
2355
mandos_dbus_service.ClientRemoved(client
2008
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2358
client_settings.clear()
2360
2011
atexit.register(cleanup)
2362
for client in tcp_server.clients.itervalues():
2013
for client in tcp_server.clients:
2364
2015
# Emit D-Bus signal
2365
2016
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2366
# Need to initiate checking of clients
2368
client.init_checker()
2371
2019
tcp_server.enable()
2372
2020
tcp_server.server_activate()