86
82
SO_BINDTODEVICE = None
90
stored_state_path = "/var/lib/mandos/clients.pickle"
92
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
93
89
syslogger = (logging.handlers.SysLogHandler
94
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
91
address = str("/dev/log")))
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
101
except (OSError, AttributeError):
102
def if_nametoindex(interface):
103
"Get an interface index the hard way, i.e. using fcntl()"
104
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
105
with contextlib.closing(socket.socket()) as s:
106
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
struct.pack(str("16s16x"),
109
interface_index = struct.unpack(str("I"),
111
return interface_index
114
def initlogger(level=logging.WARNING):
115
"""init logger and add loglevel"""
117
syslogger.setFormatter(logging.Formatter
118
('Mandos [%(process)d]: %(levelname)s:'
120
logger.addHandler(syslogger)
122
console = logging.StreamHandler()
123
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
127
logger.addHandler(console)
128
logger.setLevel(level)
131
class CryptoError(Exception):
135
class Crypto(object):
136
"""A simple class for OpenPGP symmetric encryption & decryption"""
138
self.gnupg = GnuPGInterface.GnuPG()
139
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
self.gnupg = GnuPGInterface.GnuPG()
141
self.gnupg.options.meta_interactive = False
142
self.gnupg.options.homedir = self.tempdir
143
self.gnupg.options.extra_args.extend(['--force-mdc',
149
def __exit__ (self, exc_type, exc_value, traceback):
157
if self.tempdir is not None:
158
# Delete contents of tempdir
159
for root, dirs, files in os.walk(self.tempdir,
161
for filename in files:
162
os.remove(os.path.join(root, filename))
164
os.rmdir(os.path.join(root, dirname))
166
os.rmdir(self.tempdir)
169
def password_encode(self, password):
170
# Passphrase can not be empty and can not contain newlines or
171
# NUL bytes. So we prefix it and hex encode it.
172
return b"mandos" + binascii.hexlify(password)
174
def encrypt(self, data, password):
175
self.gnupg.passphrase = self.password_encode(password)
176
with open(os.devnull) as devnull:
178
proc = self.gnupg.run(['--symmetric'],
179
create_fhs=['stdin', 'stdout'],
180
attach_fhs={'stderr': devnull})
181
with contextlib.closing(proc.handles['stdin']) as f:
183
with contextlib.closing(proc.handles['stdout']) as f:
184
ciphertext = f.read()
188
self.gnupg.passphrase = None
191
def decrypt(self, data, password):
192
self.gnupg.passphrase = self.password_encode(password)
193
with open(os.devnull) as devnull:
195
proc = self.gnupg.run(['--decrypt'],
196
create_fhs=['stdin', 'stdout'],
197
attach_fhs={'stderr': devnull})
198
with contextlib.closing(proc.handles['stdin'] ) as f:
200
with contextlib.closing(proc.handles['stdout']) as f:
201
decrypted_plaintext = f.read()
205
self.gnupg.passphrase = None
206
return decrypted_plaintext
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)
210
103
class AvahiError(Exception):
211
104
def __init__(self, value, *args, **kwargs):
431
313
"created", "enabled", "fingerprint",
432
314
"host", "interval", "last_checked_ok",
433
315
"last_enabled", "name", "timeout")
435
317
def timeout_milliseconds(self):
436
318
"Return the 'timeout' attribute in milliseconds"
437
319
return _timedelta_to_milliseconds(self.timeout)
439
321
def extended_timeout_milliseconds(self):
440
322
"Return the 'extended_timeout' attribute in milliseconds"
441
return _timedelta_to_milliseconds(self.extended_timeout)
323
return _timedelta_to_milliseconds(self.extended_timeout)
443
325
def interval_milliseconds(self):
444
326
"Return the 'interval' attribute in milliseconds"
445
327
return _timedelta_to_milliseconds(self.interval)
447
329
def approval_delay_milliseconds(self):
448
330
return _timedelta_to_milliseconds(self.approval_delay)
450
def __init__(self, name = None, config=None):
332
def __init__(self, name = None, disable_hook=None, config=None):
451
333
"""Note: the 'checker' key in 'config' sets the
452
334
'checker_command' attribute and *not* the 'checker'
474
356
self.host = config.get("host", "")
475
357
self.created = datetime.datetime.utcnow()
477
359
self.last_approval_request = None
478
self.last_enabled = datetime.datetime.utcnow()
360
self.last_enabled = None
479
361
self.last_checked_ok = None
480
self.last_checker_status = None
481
362
self.timeout = string_to_delta(config["timeout"])
482
self.extended_timeout = string_to_delta(config
483
["extended_timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
484
364
self.interval = string_to_delta(config["interval"])
365
self.disable_hook = disable_hook
485
366
self.checker = None
486
367
self.checker_initiator_tag = None
487
368
self.disable_initiator_tag = None
488
self.expires = datetime.datetime.utcnow() + self.timeout
489
370
self.checker_callback_tag = None
490
371
self.checker_command = config["checker"]
491
372
self.current_checker_command = None
373
self.last_connect = None
492
374
self._approved = None
493
375
self.approved_by_default = config.get("approved_by_default",
497
379
config["approval_delay"])
498
380
self.approval_duration = string_to_delta(
499
381
config["approval_duration"])
500
self.changedstate = (multiprocessing_manager
501
.Condition(multiprocessing_manager
503
self.client_structure = [attr for attr in
504
self.__dict__.iterkeys()
505
if not attr.startswith("_")]
506
self.client_structure.append("client_structure")
508
for name, t in inspect.getmembers(type(self),
512
if not name.startswith("_"):
513
self.client_structure.append(name)
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
515
# Send notice to process children that client state has changed
516
384
def send_changedstate(self):
517
with self.changedstate:
518
self.changedstate.notify_all()
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
520
389
def enable(self):
521
390
"""Start this client's checker and timeout hooks"""
522
391
if getattr(self, "enabled", False):
523
392
# Already enabled
525
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
526
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
self.disable_initiator_tag = (gobject.timeout_add
403
(self.timeout_milliseconds(),
527
405
self.enabled = True
528
406
self.last_enabled = datetime.datetime.utcnow()
407
# Also start a new checker *right now*.
531
410
def disable(self, quiet=True):
532
411
"""Disable this client."""
544
423
gobject.source_remove(self.checker_initiator_tag)
545
424
self.checker_initiator_tag = None
546
425
self.stop_checker()
426
if self.disable_hook:
427
self.disable_hook(self)
547
428
self.enabled = False
548
429
# Do not run this again if called by a gobject.timeout_add
551
432
def __del__(self):
433
self.disable_hook = None
554
def init_checker(self):
555
# Schedule a new checker to be started an 'interval' from now,
556
# and every interval from then on.
557
self.checker_initiator_tag = (gobject.timeout_add
558
(self.interval_milliseconds(),
560
# Schedule a disable() when 'timeout' has passed
561
self.disable_initiator_tag = (gobject.timeout_add
562
(self.timeout_milliseconds(),
564
# Also start a new checker *right now*.
567
436
def checker_callback(self, pid, condition, command):
568
437
"""The checker has completed, so take appropriate actions."""
569
438
self.checker_callback_tag = None
570
439
self.checker = None
571
440
if os.WIFEXITED(condition):
572
self.last_checker_status = os.WEXITSTATUS(condition)
573
if self.last_checker_status == 0:
441
exitstatus = os.WEXITSTATUS(condition)
574
443
logger.info("Checker for %(name)s succeeded",
576
445
self.checked_ok()
591
459
if timeout is None:
592
460
timeout = self.timeout
593
461
self.last_checked_ok = datetime.datetime.utcnow()
594
if self.disable_initiator_tag is not None:
595
gobject.source_remove(self.disable_initiator_tag)
596
if getattr(self, "enabled", False):
597
self.disable_initiator_tag = (gobject.timeout_add
598
(_timedelta_to_milliseconds
599
(timeout), self.disable))
600
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),
602
468
def need_approval(self):
603
469
self.last_approval_request = datetime.datetime.utcnow()
760
625
def _get_all_dbus_properties(self):
761
626
"""Returns a generator of (name, attribute) pairs
763
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
764
for cls in self.__class__.__mro__
628
return ((prop._dbus_name, prop)
765
629
for name, prop in
766
inspect.getmembers(cls, self._is_dbus_property))
630
inspect.getmembers(self, self._is_dbus_property))
768
632
def _get_dbus_property(self, interface_name, property_name):
769
633
"""Returns a bound method if one exists which is a D-Bus
770
634
property with the specified name and interface.
772
for cls in self.__class__.__mro__:
773
for name, value in (inspect.getmembers
774
(cls, self._is_dbus_property)):
775
if (value._dbus_name == property_name
776
and value._dbus_interface == interface_name):
777
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)):
779
646
# No such property
780
647
raise DBusPropertyNotFound(self.dbus_object_path + ":"
781
648
+ interface_name + "."
890
757
return dbus.String(dt.isoformat(),
891
758
variant_level=variant_level)
894
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
896
"""Applied to an empty subclass of a D-Bus object, this metaclass
897
will add additional D-Bus attributes matching a certain pattern.
899
def __new__(mcs, name, bases, attr):
900
# Go through all the base classes which could have D-Bus
901
# methods, signals, or properties in them
902
for base in (b for b in bases
903
if issubclass(b, dbus.service.Object)):
904
# Go though all attributes of the base class
905
for attrname, attribute in inspect.getmembers(base):
906
# Ignore non-D-Bus attributes, and D-Bus attributes
907
# with the wrong interface name
908
if (not hasattr(attribute, "_dbus_interface")
909
or not attribute._dbus_interface
910
.startswith("se.recompile.Mandos")):
912
# Create an alternate D-Bus interface name based on
914
alt_interface = (attribute._dbus_interface
915
.replace("se.recompile.Mandos",
916
"se.bsnet.fukt.Mandos"))
917
# Is this a D-Bus signal?
918
if getattr(attribute, "_dbus_is_signal", False):
919
# Extract the original non-method function by
921
nonmethod_func = (dict(
922
zip(attribute.func_code.co_freevars,
923
attribute.__closure__))["func"]
925
# Create a new, but exactly alike, function
926
# object, and decorate it to be a new D-Bus signal
927
# with the alternate D-Bus interface name
928
new_function = (dbus.service.signal
930
attribute._dbus_signature)
932
nonmethod_func.func_code,
933
nonmethod_func.func_globals,
934
nonmethod_func.func_name,
935
nonmethod_func.func_defaults,
936
nonmethod_func.func_closure)))
937
# Define a creator of a function to call both the
938
# old and new functions, so both the old and new
939
# signals gets sent when the function is called
940
def fixscope(func1, func2):
941
"""This function is a scope container to pass
942
func1 and func2 to the "call_both" function
943
outside of its arguments"""
944
def call_both(*args, **kwargs):
945
"""This function will emit two D-Bus
946
signals by calling func1 and func2"""
947
func1(*args, **kwargs)
948
func2(*args, **kwargs)
950
# Create the "call_both" function and add it to
952
attr[attrname] = fixscope(attribute,
954
# Is this a D-Bus method?
955
elif getattr(attribute, "_dbus_is_method", False):
956
# Create a new, but exactly alike, function
957
# object. Decorate it to be a new D-Bus method
958
# with the alternate D-Bus interface name. Add it
960
attr[attrname] = (dbus.service.method
962
attribute._dbus_in_signature,
963
attribute._dbus_out_signature)
965
(attribute.func_code,
966
attribute.func_globals,
968
attribute.func_defaults,
969
attribute.func_closure)))
970
# Is this a D-Bus property?
971
elif getattr(attribute, "_dbus_is_property", False):
972
# Create a new, but exactly alike, function
973
# object, and decorate it to be a new D-Bus
974
# property with the alternate D-Bus interface
975
# name. Add it to the class.
976
attr[attrname] = (dbus_service_property
978
attribute._dbus_signature,
979
attribute._dbus_access,
981
._dbus_get_args_options
984
(attribute.func_code,
985
attribute.func_globals,
987
attribute.func_defaults,
988
attribute.func_closure)))
989
return type.__new__(mcs, name, bases, attr)
992
760
class ClientDBus(Client, DBusObjectWithProperties):
993
761
"""A Client class using D-Bus
1020
787
def notifychangeproperty(transform_func,
1021
788
dbus_name, type_func=lambda x: x,
1022
789
variant_level=1):
1023
""" Modify a variable so that it's a property which announces
1024
its changes to DBus.
1026
transform_fun: Function that takes a value and a variant_level
1027
and transforms it to a D-Bus type.
1028
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
1029
795
type_func: Function that transform the value before sending it
1030
to the D-Bus. Default: no transform
1031
variant_level: D-Bus variant level. Default: 1
797
variant_level: DBus variant level. default: 1
1033
attrname = "_{0}".format(dbus_name)
1034
800
def setter(self, value):
801
old_value = real_value[0]
802
real_value[0] = value
1035
803
if hasattr(self, "dbus_object_path"):
1036
if (not hasattr(self, attrname) or
1037
type_func(getattr(self, attrname, None))
1038
!= type_func(value)):
1039
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]),
1042
807
self.PropertyChanged(dbus.String(dbus_name),
1044
setattr(self, attrname, value)
1046
return property(lambda self: getattr(self, attrname), setter)
810
return property(lambda self: real_value[0], setter)
1049
813
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1050
814
approvals_pending = notifychangeproperty(dbus.Boolean,
1051
815
"ApprovalPending",
1054
818
last_enabled = notifychangeproperty(datetime_to_dbus,
1056
820
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1057
type_func = lambda checker:
1058
checker is not None)
821
type_func = lambda checker: checker is not None)
1059
822
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1060
823
"LastCheckedOK")
1061
last_approval_request = notifychangeproperty(
1062
datetime_to_dbus, "LastApprovalRequest")
824
last_approval_request = notifychangeproperty(datetime_to_dbus,
825
"LastApprovalRequest")
1063
826
approved_by_default = notifychangeproperty(dbus.Boolean,
1064
827
"ApprovedByDefault")
1065
approval_delay = notifychangeproperty(dbus.UInt16,
1068
_timedelta_to_milliseconds)
1069
approval_duration = notifychangeproperty(
1070
dbus.UInt16, "ApprovalDuration",
1071
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)
1072
832
host = notifychangeproperty(dbus.String, "Host")
1073
833
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1075
_timedelta_to_milliseconds)
1076
extended_timeout = notifychangeproperty(
1077
dbus.UInt16, "ExtendedTimeout",
1078
type_func = _timedelta_to_milliseconds)
1079
interval = notifychangeproperty(dbus.UInt16,
1082
_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)
1083
839
checker_command = notifychangeproperty(dbus.String, "Checker")
1085
841
del notifychangeproperty
1441
1185
unicode(self.client_address))
1442
1186
logger.debug("Pipe FD: %d",
1443
1187
self.server.child_pipe.fileno())
1445
1189
session = (gnutls.connection
1446
1190
.ClientSession(self.request,
1447
1191
gnutls.connection
1448
1192
.X509Credentials()))
1450
1194
# Note: gnutls.connection.X509Credentials is really a
1451
1195
# generic GnuTLS certificate credentials object so long as
1452
1196
# no X.509 keys are added to it. Therefore, we can use it
1453
1197
# here despite using OpenPGP certificates.
1455
1199
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1456
1200
# "+AES-256-CBC", "+SHA1",
1457
1201
# "+COMP-NULL", "+CTYPE-OPENPGP",
1677
1413
This function creates a new pipe in self.pipe
1679
1415
parent_pipe, self.child_pipe = multiprocessing.Pipe()
1681
proc = MultiprocessingMixIn.process_request(self, request,
1417
super(MultiprocessingMixInWithPipe,
1418
self).process_request(request, client_address)
1683
1419
self.child_pipe.close()
1684
self.add_pipe(parent_pipe, proc)
1686
def add_pipe(self, parent_pipe, proc):
1420
self.add_pipe(parent_pipe)
1422
def add_pipe(self, parent_pipe):
1687
1423
"""Dummy function; override as necessary"""
1688
1424
raise NotImplementedError
1691
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1692
1427
socketserver.TCPServer, object):
1693
1428
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
1777
1512
def server_activate(self):
1778
1513
if self.enabled:
1779
1514
return socketserver.TCPServer.server_activate(self)
1781
1515
def enable(self):
1782
1516
self.enabled = True
1784
def add_pipe(self, parent_pipe, proc):
1517
def add_pipe(self, parent_pipe):
1785
1518
# Call "handle_ipc" for both data and EOF events
1786
1519
gobject.io_add_watch(parent_pipe.fileno(),
1787
1520
gobject.IO_IN | gobject.IO_HUP,
1788
1521
functools.partial(self.handle_ipc,
1522
parent_pipe = parent_pipe))
1793
1524
def handle_ipc(self, source, condition, parent_pipe=None,
1794
proc = None, client_object=None):
1525
client_object=None):
1795
1526
condition_names = {
1796
1527
gobject.IO_IN: "IN", # There is data to read.
1797
1528
gobject.IO_OUT: "OUT", # Data can be written (without
1829
1558
"dress: %s", fpr, address)
1830
1559
if self.use_dbus:
1831
1560
# Emit D-Bus signal
1832
mandos_dbus_service.ClientNotFound(fpr,
1561
mandos_dbus_service.ClientNotFound(fpr, address[0])
1834
1562
parent_pipe.send(False)
1837
1565
gobject.io_add_watch(parent_pipe.fileno(),
1838
1566
gobject.IO_IN | gobject.IO_HUP,
1839
1567
functools.partial(self.handle_ipc,
1568
parent_pipe = parent_pipe,
1569
client_object = client))
1845
1570
parent_pipe.send(True)
1846
# 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
1849
1573
if command == 'funcall':
1850
1574
funcname = request[1]
1851
1575
args = request[2]
1852
1576
kwargs = request[3]
1854
parent_pipe.send(('data', getattr(client_object,
1578
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1858
1580
if command == 'getattr':
1859
1581
attrname = request[1]
1860
1582
if callable(client_object.__getattribute__(attrname)):
1861
1583
parent_pipe.send(('function',))
1863
parent_pipe.send(('data', client_object
1864
.__getattribute__(attrname)))
1585
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1866
1587
if command == 'setattr':
1867
1588
attrname = request[1]
1868
1589
value = request[2]
1869
1590
setattr(client_object, attrname, value)
1910
1631
return timevalue
1634
def if_nametoindex(interface):
1635
"""Call the C function if_nametoindex(), or equivalent
1637
Note: This function cannot accept a unicode string."""
1638
global if_nametoindex
1640
if_nametoindex = (ctypes.cdll.LoadLibrary
1641
(ctypes.util.find_library("c"))
1643
except (OSError, AttributeError):
1644
logger.warning("Doing if_nametoindex the hard way")
1645
def if_nametoindex(interface):
1646
"Get an interface index the hard way, i.e. using fcntl()"
1647
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1648
with contextlib.closing(socket.socket()) as s:
1649
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1650
struct.pack(str("16s16x"),
1652
interface_index = struct.unpack(str("I"),
1654
return interface_index
1655
return if_nametoindex(interface)
1913
1658
def daemon(nochdir = False, noclose = False):
1914
1659
"""See daemon(3). Standard BSD Unix function.
2137
1877
# End of Avahi example code
2140
bus_name = dbus.service.BusName("se.recompile.Mandos",
1880
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2141
1881
bus, do_not_queue=True)
2142
old_bus_name = (dbus.service.BusName
2143
("se.bsnet.fukt.Mandos", bus,
2145
1882
except dbus.exceptions.NameExistsException as e:
2146
1883
logger.error(unicode(e) + ", disabling D-Bus")
2147
1884
use_dbus = False
2148
1885
server_settings["use_dbus"] = False
2149
1886
tcp_server.use_dbus = False
2150
1887
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2151
service = AvahiServiceToSyslog(name =
2152
server_settings["servicename"],
2153
servicetype = "_mandos._tcp",
2154
protocol = protocol, bus = bus)
1888
service = AvahiService(name = server_settings["servicename"],
1889
servicetype = "_mandos._tcp",
1890
protocol = protocol, bus = bus)
2155
1891
if server_settings["interface"]:
2156
1892
service.interface = (if_nametoindex
2157
1893
(str(server_settings["interface"])))
2162
1898
client_class = Client
2164
client_class = functools.partial(ClientDBusTransitional,
2167
special_settings = {
2168
# Some settings need to be accessd by special methods;
2169
# booleans need .getboolean(), etc. Here is a list of them:
2170
"approved_by_default":
2172
client_config.getboolean(section, "approved_by_default"),
2174
# Construct a new dict of client settings of this form:
2175
# { client_name: {setting_name: value, ...}, ...}
2176
# with exceptions for any special settings as defined above
2177
client_settings = dict((clientname,
2180
if setting not in special_settings
2181
else special_settings[setting]
2183
for setting, value in
2184
client_config.items(clientname)))
2185
for clientname in client_config.sections())
2187
old_client_settings = {}
2190
# Get client data and settings from last running state.
2191
if server_settings["restore"]:
2193
with open(stored_state_path, "rb") as stored_state:
2194
clients_data, old_client_settings = (pickle.load
2196
os.remove(stored_state_path)
2197
except IOError as e:
2198
logger.warning("Could not load persistent state: {0}"
2200
if e.errno != errno.ENOENT:
2203
with Crypto() as crypt:
2204
for client in clients_data:
2205
client_name = client["name"]
2207
# Decide which value to use after restoring saved state.
2208
# We have three different values: Old config file,
2209
# new config file, and saved state.
2210
# New config value takes precedence if it differs from old
2211
# config value, otherwise use saved state.
2212
for name, value in client_settings[client_name].items():
2214
# For each value in new config, check if it
2215
# differs from the old config value (Except for
2216
# the "secret" attribute)
2217
if (name != "secret" and
2218
value != old_client_settings[client_name]
2220
setattr(client, name, value)
2224
# Clients who has passed its expire date can still be
2225
# enabled if its last checker was sucessful. Clients
2226
# whose checker failed before we stored its state is
2227
# assumed to have failed all checkers during downtime.
2228
if client["enabled"] and client["last_checked_ok"]:
2229
if ((datetime.datetime.utcnow()
2230
- client["last_checked_ok"])
2231
> client["interval"]):
2232
if client["last_checker_status"] != 0:
2233
client["enabled"] = False
2235
client["expires"] = (datetime.datetime
2237
+ client["timeout"])
2239
client["changedstate"] = (multiprocessing_manager
2241
(multiprocessing_manager
2244
new_client = (ClientDBusTransitional.__new__
2245
(ClientDBusTransitional))
2246
tcp_server.clients[client_name] = new_client
2247
new_client.bus = bus
2248
for name, value in client.iteritems():
2249
setattr(new_client, name, value)
2250
client_object_name = unicode(client_name).translate(
2251
{ord("."): ord("_"),
2252
ord("-"): ord("_")})
2253
new_client.dbus_object_path = (dbus.ObjectPath
2255
+ client_object_name))
2256
DBusObjectWithProperties.__init__(new_client,
2261
tcp_server.clients[client_name] = (Client.__new__
2263
for name, value in client.iteritems():
2264
setattr(tcp_server.clients[client_name],
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):
2268
tcp_server.clients[client_name].secret = (
2269
crypt.decrypt(tcp_server.clients[client_name]
2271
client_settings[client_name]
2274
# If decryption fails, we use secret from new settings
2275
tcp_server.clients[client_name].secret = (
2276
client_settings[client_name]["secret"])
2278
# Create/remove clients based on new changes made to config
2279
for clientname in set(old_client_settings) - set(client_settings):
2280
del tcp_server.clients[clientname]
2281
for clientname in set(client_settings) - set(old_client_settings):
2282
tcp_server.clients[clientname] = (client_class(name
1909
yield (name, special_settings[name]())
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()))
2288
1918
if not tcp_server.clients:
2289
1919
logger.warning("No clients defined")
2364
class MandosDBusServiceTransitional(MandosDBusService):
2365
__metaclass__ = AlternateDBusNamesMetaclass
2366
mandos_dbus_service = MandosDBusServiceTransitional()
1993
mandos_dbus_service = MandosDBusService()
2369
1996
"Cleanup function; run on exit"
2370
1997
service.cleanup()
2372
multiprocessing.active_children()
2373
if not (tcp_server.clients or client_settings):
2376
# Store client before exiting. Secrets are encrypted with key
2377
# based on what config file has. If config file is
2378
# removed/edited, old secret will thus be unrecovable.
2380
with Crypto() as crypt:
2381
for client in tcp_server.clients.itervalues():
2382
key = client_settings[client.name]["secret"]
2383
client.encrypted_secret = crypt.encrypt(client.secret,
2387
# A list of attributes that will not be stored when
2389
exclude = set(("bus", "changedstate", "secret"))
2390
for name, typ in (inspect.getmembers
2391
(dbus.service.Object)):
2394
client_dict["encrypted_secret"] = (client
2396
for attr in client.client_structure:
2397
if attr not in exclude:
2398
client_dict[attr] = getattr(client, attr)
2400
clients.append(client_dict)
2401
del client_settings[client.name]["secret"]
2404
with os.fdopen(os.open(stored_state_path,
2405
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2406
0600), "wb") as stored_state:
2407
pickle.dump((clients, client_settings), stored_state)
2408
except (IOError, OSError) as e:
2409
logger.warning("Could not save persistent state: {0}"
2411
if e.errno not in (errno.ENOENT, errno.EACCES):
2414
# Delete all clients, and settings from config
2415
1999
while tcp_server.clients:
2416
name, client = tcp_server.clients.popitem()
2000
client = tcp_server.clients.pop()
2418
2002
client.remove_from_connection()
2003
client.disable_hook = None
2419
2004
# Don't signal anything except ClientRemoved
2420
2005
client.disable(quiet=True)
2422
2007
# Emit D-Bus signal
2423
mandos_dbus_service.ClientRemoved(client
2008
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2426
client_settings.clear()
2428
2011
atexit.register(cleanup)
2430
for client in tcp_server.clients.itervalues():
2013
for client in tcp_server.clients:
2432
2015
# Emit D-Bus signal
2433
2016
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2434
# Need to initiate checking of clients
2436
client.init_checker()
2438
2019
tcp_server.enable()
2439
2020
tcp_server.server_activate()