88
84
except ImportError:
89
85
SO_BINDTODEVICE = None
92
stored_state_file = "clients.pickle"
94
90
logger = logging.getLogger()
91
stored_state_path = "/var/lib/mandos/clients.pickle"
95
93
syslogger = (logging.handlers.SysLogHandler
96
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
97
95
address = str("/dev/log")))
100
if_nametoindex = (ctypes.cdll.LoadLibrary
101
(ctypes.util.find_library("c"))
103
except (OSError, AttributeError):
104
def if_nametoindex(interface):
105
"Get an interface index the hard way, i.e. using fcntl()"
106
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
107
with contextlib.closing(socket.socket()) as s:
108
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
113
return interface_index
116
def initlogger(debug, level=logging.WARNING):
117
"""init logger and add loglevel"""
119
syslogger.setFormatter(logging.Formatter
120
('Mandos [%(process)d]: %(levelname)s:'
122
logger.addHandler(syslogger)
125
console = logging.StreamHandler()
126
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
130
logger.addHandler(console)
131
logger.setLevel(level)
134
class PGPError(Exception):
135
"""Exception if encryption/decryption fails"""
139
class PGPEngine(object):
140
"""A simple class for OpenPGP symmetric encryption & decryption"""
142
self.gnupg = GnuPGInterface.GnuPG()
143
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
144
self.gnupg = GnuPGInterface.GnuPG()
145
self.gnupg.options.meta_interactive = False
146
self.gnupg.options.homedir = self.tempdir
147
self.gnupg.options.extra_args.extend(['--force-mdc',
154
def __exit__ (self, exc_type, exc_value, traceback):
162
if self.tempdir is not None:
163
# Delete contents of tempdir
164
for root, dirs, files in os.walk(self.tempdir,
166
for filename in files:
167
os.remove(os.path.join(root, filename))
169
os.rmdir(os.path.join(root, dirname))
171
os.rmdir(self.tempdir)
174
def password_encode(self, password):
175
# Passphrase can not be empty and can not contain newlines or
176
# NUL bytes. So we prefix it and hex encode it.
177
return b"mandos" + binascii.hexlify(password)
179
def encrypt(self, data, password):
180
self.gnupg.passphrase = self.password_encode(password)
181
with open(os.devnull, "w") as devnull:
183
proc = self.gnupg.run(['--symmetric'],
184
create_fhs=['stdin', 'stdout'],
185
attach_fhs={'stderr': devnull})
186
with contextlib.closing(proc.handles['stdin']) as f:
188
with contextlib.closing(proc.handles['stdout']) as f:
189
ciphertext = f.read()
193
self.gnupg.passphrase = None
196
def decrypt(self, data, password):
197
self.gnupg.passphrase = self.password_encode(password)
198
with open(os.devnull, "w") as devnull:
200
proc = self.gnupg.run(['--decrypt'],
201
create_fhs=['stdin', 'stdout'],
202
attach_fhs={'stderr': devnull})
203
with contextlib.closing(proc.handles['stdin']) as f:
205
with contextlib.closing(proc.handles['stdout']) as f:
206
decrypted_plaintext = f.read()
210
self.gnupg.passphrase = None
211
return decrypted_plaintext
96
syslogger.setFormatter(logging.Formatter
97
('Mandos [%(process)d]: %(levelname)s:'
99
logger.addHandler(syslogger)
101
console = logging.StreamHandler()
102
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
106
logger.addHandler(console)
214
109
class AvahiError(Exception):
426
310
interval: datetime.timedelta(); How often to start a new checker
427
311
last_approval_request: datetime.datetime(); (UTC) or None
428
312
last_checked_ok: datetime.datetime(); (UTC) or None
429
last_checker_status: integer between 0 and 255 reflecting exit
430
status of last checker. -1 reflects crashed
431
checker, -2 means no checker completed yet.
432
last_enabled: datetime.datetime(); (UTC) or None
313
last_checker_status: integer between 0 and 255 reflecting exit status
314
of last checker. -1 reflect crashed checker,
316
last_enabled: datetime.datetime(); (UTC)
433
317
name: string; from the config file, used in log messages and
434
318
D-Bus identifiers
435
319
secret: bytestring; sent verbatim (over TLS) to client
436
320
timeout: datetime.timedelta(); How long from last_checked_ok
437
321
until this client is disabled
438
extended_timeout: extra long timeout when secret has been sent
322
extended_timeout: extra long timeout when password has been sent
439
323
runtime_expansions: Allowed attributes for runtime expansion.
440
324
expires: datetime.datetime(); time (UTC) when a client will be
441
325
disabled, or None
444
328
runtime_expansions = ("approval_delay", "approval_duration",
445
"created", "enabled", "expires",
446
"fingerprint", "host", "interval",
447
"last_approval_request", "last_checked_ok",
329
"created", "enabled", "fingerprint",
330
"host", "interval", "last_checked_ok",
448
331
"last_enabled", "name", "timeout")
449
client_defaults = { "timeout": "5m",
450
"extended_timeout": "15m",
452
"checker": "fping -q -- %%(host)s",
454
"approval_delay": "0s",
455
"approval_duration": "1s",
456
"approved_by_default": "True",
460
333
def timeout_milliseconds(self):
461
334
"Return the 'timeout' attribute in milliseconds"
462
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
464
337
def extended_timeout_milliseconds(self):
465
338
"Return the 'extended_timeout' attribute in milliseconds"
466
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
468
341
def interval_milliseconds(self):
469
342
"Return the 'interval' attribute in milliseconds"
470
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
472
345
def approval_delay_milliseconds(self):
473
return timedelta_to_milliseconds(self.approval_delay)
476
def config_parser(config):
477
"""Construct a new dict of client settings of this form:
478
{ client_name: {setting_name: value, ...}, ...}
479
with exceptions for any special settings as defined above.
480
NOTE: Must be a pure function. Must return the same result
481
value given the same arguments.
484
for client_name in config.sections():
485
section = dict(config.items(client_name))
486
client = settings[client_name] = {}
488
client["host"] = section["host"]
489
# Reformat values from string types to Python types
490
client["approved_by_default"] = config.getboolean(
491
client_name, "approved_by_default")
492
client["enabled"] = config.getboolean(client_name,
495
client["fingerprint"] = (section["fingerprint"].upper()
497
if "secret" in section:
498
client["secret"] = section["secret"].decode("base64")
499
elif "secfile" in section:
500
with open(os.path.expanduser(os.path.expandvars
501
(section["secfile"])),
503
client["secret"] = secfile.read()
505
raise TypeError("No secret or secfile for section {0}"
507
client["timeout"] = string_to_delta(section["timeout"])
508
client["extended_timeout"] = string_to_delta(
509
section["extended_timeout"])
510
client["interval"] = string_to_delta(section["interval"])
511
client["approval_delay"] = string_to_delta(
512
section["approval_delay"])
513
client["approval_duration"] = string_to_delta(
514
section["approval_duration"])
515
client["checker_command"] = section["checker"]
516
client["last_approval_request"] = None
517
client["last_checked_ok"] = None
518
client["last_checker_status"] = -2
522
def __init__(self, settings, name = None):
346
return _timedelta_to_milliseconds(self.approval_delay)
348
def __init__(self, name = None, config=None):
349
"""Note: the 'checker' key in 'config' sets the
350
'checker_command' attribute and *not* the 'checker'
524
# adding all client settings
525
for setting, value in settings.iteritems():
526
setattr(self, setting, value)
529
if not hasattr(self, "last_enabled"):
530
self.last_enabled = datetime.datetime.utcnow()
531
if not hasattr(self, "expires"):
532
self.expires = (datetime.datetime.utcnow()
535
self.last_enabled = None
538
355
logger.debug("Creating client %r", self.name)
539
356
# Uppercase and remove spaces from fingerprint for later
540
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
542
361
logger.debug(" Fingerprint: %s", self.fingerprint)
543
self.created = settings.get("created",
544
datetime.datetime.utcnow())
546
# attributes specific for this server instance
362
if "secret" in config:
363
self.secret = config["secret"].decode("base64")
364
elif "secfile" in config:
365
with open(os.path.expanduser(os.path.expandvars
366
(config["secfile"])),
368
self.secret = secfile.read()
370
raise TypeError("No secret or secfile for client %s"
372
self.host = config.get("host", "")
373
self.created = datetime.datetime.utcnow()
375
self.last_approval_request = None
376
self.last_enabled = datetime.datetime.utcnow()
377
self.last_checked_ok = None
378
self.last_checker_status = None
379
self.timeout = string_to_delta(config["timeout"])
380
self.extended_timeout = string_to_delta(config
381
["extended_timeout"])
382
self.interval = string_to_delta(config["interval"])
547
383
self.checker = None
548
384
self.checker_initiator_tag = None
549
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
550
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
551
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
553
393
self.approvals_pending = 0
394
self.approval_delay = string_to_delta(
395
config["approval_delay"])
396
self.approval_duration = string_to_delta(
397
config["approval_duration"])
554
398
self.changedstate = (multiprocessing_manager
555
399
.Condition(multiprocessing_manager
557
self.client_structure = [attr for attr in
558
self.__dict__.iterkeys()
559
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
560
402
self.client_structure.append("client_structure")
562
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
566
407
if not name.startswith("_"):
567
408
self.client_structure.append(name)
576
417
if getattr(self, "enabled", False):
577
418
# Already enabled
420
self.send_changedstate()
579
421
self.expires = datetime.datetime.utcnow() + self.timeout
580
422
self.enabled = True
581
423
self.last_enabled = datetime.datetime.utcnow()
582
424
self.init_checker()
583
self.send_changedstate()
585
426
def disable(self, quiet=True):
586
427
"""Disable this client."""
587
428
if not getattr(self, "enabled", False):
431
self.send_changedstate()
590
433
logger.info("Disabling client %s", self.name)
591
if getattr(self, "disable_initiator_tag", None) is not None:
434
if getattr(self, "disable_initiator_tag", False):
592
435
gobject.source_remove(self.disable_initiator_tag)
593
436
self.disable_initiator_tag = None
594
437
self.expires = None
595
if getattr(self, "checker_initiator_tag", None) is not None:
438
if getattr(self, "checker_initiator_tag", False):
596
439
gobject.source_remove(self.checker_initiator_tag)
597
440
self.checker_initiator_tag = None
598
441
self.stop_checker()
599
442
self.enabled = False
601
self.send_changedstate()
602
443
# Do not run this again if called by a gobject.timeout_add
605
446
def __del__(self):
608
449
def init_checker(self):
609
450
# Schedule a new checker to be started an 'interval' from now,
610
451
# and every interval from then on.
611
if self.checker_initiator_tag is not None:
612
gobject.source_remove(self.checker_initiator_tag)
613
452
self.checker_initiator_tag = (gobject.timeout_add
614
453
(self.interval_milliseconds(),
615
454
self.start_checker))
616
455
# Schedule a disable() when 'timeout' has passed
617
if self.disable_initiator_tag is not None:
618
gobject.source_remove(self.disable_initiator_tag)
619
456
self.disable_initiator_tag = (gobject.timeout_add
620
457
(self.timeout_milliseconds(),
622
459
# Also start a new checker *right now*.
623
460
self.start_checker()
625
463
def checker_callback(self, pid, condition, command):
626
464
"""The checker has completed, so take appropriate actions."""
627
465
self.checker_callback_tag = None
628
466
self.checker = None
629
467
if os.WIFEXITED(condition):
630
self.last_checker_status = os.WEXITSTATUS(condition)
468
self.last_checker_status = os.WEXITSTATUS(condition)
631
469
if self.last_checker_status == 0:
632
470
logger.info("Checker for %(name)s succeeded",
739
583
logger.debug("Stopping checker for %(name)s", vars(self))
741
self.checker.terminate()
585
os.kill(self.checker.pid, signal.SIGTERM)
743
587
#if self.checker.poll() is None:
744
# self.checker.kill()
588
# os.kill(self.checker.pid, signal.SIGKILL)
745
589
except OSError as error:
746
590
if error.errno != errno.ESRCH: # No such process
748
592
self.checker = None
594
# Encrypts a client secret and stores it in a varible encrypted_secret
595
def encrypt_secret(self, key):
596
# Encryption-key need to be of a specific size, so we hash inputed key
597
hasheng = hashlib.sha256()
599
encryptionkey = hasheng.digest()
601
# Create validation hash so we know at decryption if it was sucessful
602
hasheng = hashlib.sha256()
603
hasheng.update(self.secret)
604
validationhash = hasheng.digest()
607
iv = os.urandom(Crypto.Cipher.AES.block_size)
608
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
609
Crypto.Cipher.AES.MODE_CFB, iv)
610
ciphertext = ciphereng.encrypt(validationhash+self.secret)
611
self.encrypted_secret = (ciphertext, iv)
613
# Decrypt a encrypted client secret
614
def decrypt_secret(self, key):
615
# Decryption-key need to be of a specific size, so we hash inputed key
616
hasheng = hashlib.sha256()
618
encryptionkey = hasheng.digest()
620
# Decrypt encrypted secret
621
ciphertext, iv = self.encrypted_secret
622
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
623
Crypto.Cipher.AES.MODE_CFB, iv)
624
plain = ciphereng.decrypt(ciphertext)
626
# Validate decrypted secret to know if it was succesful
627
hasheng = hashlib.sha256()
628
validationhash = plain[:hasheng.digest_size]
629
secret = plain[hasheng.digest_size:]
630
hasheng.update(secret)
632
# if validation fails, we use key as new secret. Otherwhise, we use
633
# the decrypted secret
634
if hasheng.digest() == validationhash:
638
del self.encrypted_secret
751
641
def dbus_service_property(dbus_interface, signature="v",
752
642
access="readwrite", byte_arrays=False):
954
795
e.setAttribute("access", prop._dbus_access)
956
797
for if_tag in document.getElementsByTagName("interface"):
958
798
for tag in (make_tag(document, name, prop)
960
in self._get_all_dbus_things("property")
800
in self._get_all_dbus_properties()
961
801
if prop._dbus_interface
962
802
== if_tag.getAttribute("name")):
963
803
if_tag.appendChild(tag)
964
# Add annotation tags
965
for typ in ("method", "signal", "property"):
966
for tag in if_tag.getElementsByTagName(typ):
968
for name, prop in (self.
969
_get_all_dbus_things(typ)):
970
if (name == tag.getAttribute("name")
971
and prop._dbus_interface
972
== if_tag.getAttribute("name")):
973
annots.update(getattr
977
for name, value in annots.iteritems():
978
ann_tag = document.createElement(
980
ann_tag.setAttribute("name", name)
981
ann_tag.setAttribute("value", value)
982
tag.appendChild(ann_tag)
983
# Add interface annotation tags
984
for annotation, value in dict(
985
itertools.chain.from_iterable(
986
annotations().iteritems()
987
for name, annotations in
988
self._get_all_dbus_things("interface")
989
if name == if_tag.getAttribute("name")
991
ann_tag = document.createElement("annotation")
992
ann_tag.setAttribute("name", annotation)
993
ann_tag.setAttribute("value", value)
994
if_tag.appendChild(ann_tag)
995
804
# Add the names to the return values for the
996
805
# "org.freedesktop.DBus.Properties" methods
997
806
if (if_tag.getAttribute("name")
1023
832
return dbus.String(dt.isoformat(),
1024
833
variant_level=variant_level)
1027
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1028
"""A class decorator; applied to a subclass of
1029
dbus.service.Object, it will add alternate D-Bus attributes with
1030
interface names according to the "alt_interface_names" mapping.
1033
@alternate_dbus_names({"org.example.Interface":
1034
"net.example.AlternateInterface"})
1035
class SampleDBusObject(dbus.service.Object):
1036
@dbus.service.method("org.example.Interface")
1037
def SampleDBusMethod():
1040
The above "SampleDBusMethod" on "SampleDBusObject" will be
1041
reachable via two interfaces: "org.example.Interface" and
1042
"net.example.AlternateInterface", the latter of which will have
1043
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1044
"true", unless "deprecate" is passed with a False value.
1046
This works for methods and signals, and also for D-Bus properties
1047
(from DBusObjectWithProperties) and interfaces (from the
1048
dbus_interface_annotations decorator).
835
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
837
"""Applied to an empty subclass of a D-Bus object, this metaclass
838
will add additional D-Bus attributes matching a certain pattern.
1051
for orig_interface_name, alt_interface_name in (
1052
alt_interface_names.iteritems()):
1054
interface_names = set()
1055
# Go though all attributes of the class
1056
for attrname, attribute in inspect.getmembers(cls):
840
def __new__(mcs, name, bases, attr):
841
# Go through all the base classes which could have D-Bus
842
# methods, signals, or properties in them
843
for base in (b for b in bases
844
if issubclass(b, dbus.service.Object)):
845
# Go though all attributes of the base class
846
for attrname, attribute in inspect.getmembers(base):
1057
847
# Ignore non-D-Bus attributes, and D-Bus attributes
1058
848
# with the wrong interface name
1059
849
if (not hasattr(attribute, "_dbus_interface")
1060
850
or not attribute._dbus_interface
1061
.startswith(orig_interface_name)):
851
.startswith("se.recompile.Mandos")):
1063
853
# Create an alternate D-Bus interface name based on
1064
854
# the current name
1065
855
alt_interface = (attribute._dbus_interface
1066
.replace(orig_interface_name,
1067
alt_interface_name))
1068
interface_names.add(alt_interface)
856
.replace("se.recompile.Mandos",
857
"se.bsnet.fukt.Mandos"))
1069
858
# Is this a D-Bus signal?
1070
859
if getattr(attribute, "_dbus_is_signal", False):
1071
860
# Extract the original non-method function by
1150
927
attribute.func_name,
1151
928
attribute.func_defaults,
1152
929
attribute.func_closure)))
1153
# Copy annotations, if any
1155
attr[attrname]._dbus_annotations = (
1156
dict(attribute._dbus_annotations))
1157
except AttributeError:
1159
# Is this a D-Bus interface?
1160
elif getattr(attribute, "_dbus_is_interface", False):
1161
# Create a new, but exactly alike, function
1162
# object. Decorate it to be a new D-Bus interface
1163
# with the alternate D-Bus interface name. Add it
1165
attr[attrname] = (dbus_interface_annotations
1168
(attribute.func_code,
1169
attribute.func_globals,
1170
attribute.func_name,
1171
attribute.func_defaults,
1172
attribute.func_closure)))
1174
# Deprecate all alternate interfaces
1175
iname="_AlternateDBusNames_interface_annotation{0}"
1176
for interface_name in interface_names:
1177
@dbus_interface_annotations(interface_name)
1179
return { "org.freedesktop.DBus.Deprecated":
1181
# Find an unused name
1182
for aname in (iname.format(i)
1183
for i in itertools.count()):
1184
if aname not in attr:
1188
# Replace the class with a new subclass of it with
1189
# methods, signals, etc. as created above.
1190
cls = type(b"{0}Alternate".format(cls.__name__),
1196
@alternate_dbus_interfaces({"se.recompile.Mandos":
1197
"se.bsnet.fukt.Mandos"})
930
return type.__new__(mcs, name, bases, attr)
1198
932
class ClientDBus(Client, DBusObjectWithProperties):
1199
933
"""A Client class using D-Bus
1261
998
checker is not None)
1262
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1263
1000
"LastCheckedOK")
1264
last_checker_status = notifychangeproperty(dbus.Int16,
1265
"LastCheckerStatus")
1266
1001
last_approval_request = notifychangeproperty(
1267
1002
datetime_to_dbus, "LastApprovalRequest")
1268
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1269
1004
"ApprovedByDefault")
1270
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1271
1006
"ApprovalDelay",
1273
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1274
1009
approval_duration = notifychangeproperty(
1275
dbus.UInt64, "ApprovalDuration",
1276
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1277
1012
host = notifychangeproperty(dbus.String, "Host")
1278
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1280
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1281
1016
extended_timeout = notifychangeproperty(
1282
dbus.UInt64, "ExtendedTimeout",
1283
type_func = timedelta_to_milliseconds)
1284
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1287
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1288
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1290
1025
del notifychangeproperty
2094
1830
elif suffix == "w":
2095
1831
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2097
raise ValueError("Unknown suffix {0!r}"
1833
raise ValueError("Unknown suffix %r" % suffix)
2099
1834
except (ValueError, IndexError) as e:
2100
1835
raise ValueError(*(e.args))
2101
1836
timevalue += delta
2102
1837
return timevalue
1840
def if_nametoindex(interface):
1841
"""Call the C function if_nametoindex(), or equivalent
1843
Note: This function cannot accept a unicode string."""
1844
global if_nametoindex
1846
if_nametoindex = (ctypes.cdll.LoadLibrary
1847
(ctypes.util.find_library("c"))
1849
except (OSError, AttributeError):
1850
logger.warning("Doing if_nametoindex the hard way")
1851
def if_nametoindex(interface):
1852
"Get an interface index the hard way, i.e. using fcntl()"
1853
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1854
with contextlib.closing(socket.socket()) as s:
1855
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1856
struct.pack(str("16s16x"),
1858
interface_index = struct.unpack(str("I"),
1860
return interface_index
1861
return if_nametoindex(interface)
2105
1864
def daemon(nochdir = False, noclose = False):
2106
1865
"""See daemon(3). Standard BSD Unix function.
2351
2111
client_class = Client
2353
client_class = functools.partial(ClientDBus, bus = bus)
2355
client_settings = Client.config_parser(client_config)
2113
client_class = functools.partial(ClientDBusTransitional,
2116
special_settings = {
2117
# Some settings need to be accessd by special methods;
2118
# booleans need .getboolean(), etc. Here is a list of them:
2119
"approved_by_default":
2121
client_config.getboolean(section, "approved_by_default"),
2123
# Construct a new dict of client settings of this form:
2124
# { client_name: {setting_name: value, ...}, ...}
2125
# with exceptions for any special settings as defined above
2126
client_settings = dict((clientname,
2128
(value if setting not in special_settings
2129
else special_settings[setting](clientname)))
2130
for setting, value in client_config.items(clientname)))
2131
for clientname in client_config.sections())
2356
2133
old_client_settings = {}
2359
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2360
2137
if server_settings["restore"]:
2362
2139
with open(stored_state_path, "rb") as stored_state:
2363
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2365
2141
os.remove(stored_state_path)
2366
2142
except IOError as e:
2367
if e.errno == errno.ENOENT:
2368
logger.warning("Could not load persistent state: {0}"
2369
.format(os.strerror(e.errno)))
2371
logger.critical("Could not load persistent state:",
2143
logger.warning("Could not load persistant state: {0}".format(e))
2144
if e.errno != errno.ENOENT:
2374
except EOFError as e:
2375
logger.warning("Could not load persistent state: "
2376
"EOFError:", exc_info=e)
2378
with PGPEngine() as pgp:
2379
for client_name, client in clients_data.iteritems():
2380
# Decide which value to use after restoring saved state.
2381
# We have three different values: Old config file,
2382
# new config file, and saved state.
2383
# New config value takes precedence if it differs from old
2384
# config value, otherwise use saved state.
2385
for name, value in client_settings[client_name].items():
2387
# For each value in new config, check if it
2388
# differs from the old config value (Except for
2389
# the "secret" attribute)
2390
if (name != "secret" and
2391
value != old_client_settings[client_name]
2393
client[name] = value
2397
# Clients who has passed its expire date can still be
2398
# enabled if its last checker was successful. Clients
2399
# whose checker succeeded before we stored its state is
2400
# assumed to have successfully run all checkers during
2402
if client["enabled"]:
2403
if datetime.datetime.utcnow() >= client["expires"]:
2404
if not client["last_checked_ok"]:
2406
"disabling client {0} - Client never "
2407
"performed a successful checker"
2408
.format(client_name))
2409
client["enabled"] = False
2410
elif client["last_checker_status"] != 0:
2412
"disabling client {0} - Client "
2413
"last checker failed with error code {1}"
2414
.format(client_name,
2415
client["last_checker_status"]))
2416
client["enabled"] = False
2418
client["expires"] = (datetime.datetime
2420
+ client["timeout"])
2421
logger.debug("Last checker succeeded,"
2422
" keeping {0} enabled"
2423
.format(client_name))
2147
for client in clients_data:
2148
client_name = client["name"]
2150
# Decide which value to use after restoring saved state.
2151
# We have three different values: Old config file,
2152
# new config file, and saved state.
2153
# New config value takes precedence if it differs from old
2154
# config value, otherwise use saved state.
2155
for name, value in client_settings[client_name].items():
2425
client["secret"] = (
2426
pgp.decrypt(client["encrypted_secret"],
2427
client_settings[client_name]
2430
# If decryption fails, we use secret from new settings
2431
logger.debug("Failed to decrypt {0} old secret"
2432
.format(client_name))
2433
client["secret"] = (
2434
client_settings[client_name]["secret"])
2436
# Add/remove clients based on new changes made to config
2437
for client_name in (set(old_client_settings)
2438
- set(client_settings)):
2439
del clients_data[client_name]
2440
for client_name in (set(client_settings)
2441
- set(old_client_settings)):
2442
clients_data[client_name] = client_settings[client_name]
2444
# Create all client objects
2445
for client_name, client in clients_data.iteritems():
2446
tcp_server.clients[client_name] = client_class(
2447
name = client_name, settings = client)
2157
# For each value in new config, check if it differs
2158
# from the old config value (Except for the "secret"
2160
if name != "secret" and value != old_client_settings[client_name][name]:
2161
setattr(client, name, value)
2165
# Clients who has passed its expire date, can still be enabled if its
2166
# last checker was sucessful. Clients who checkers failed before we
2167
# stored it state is asumed to had failed checker during downtime.
2168
if client["enabled"] and client["last_checked_ok"]:
2169
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2170
> client["interval"]):
2171
if client["last_checker_status"] != 0:
2172
client["enabled"] = False
2174
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2176
client["changedstate"] = (multiprocessing_manager
2177
.Condition(multiprocessing_manager
2180
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2181
tcp_server.clients[client_name] = new_client
2182
new_client.bus = bus
2183
for name, value in client.iteritems():
2184
setattr(new_client, name, value)
2185
client_object_name = unicode(client_name).translate(
2186
{ord("."): ord("_"),
2187
ord("-"): ord("_")})
2188
new_client.dbus_object_path = (dbus.ObjectPath
2189
("/clients/" + client_object_name))
2190
DBusObjectWithProperties.__init__(new_client,
2192
new_client.dbus_object_path)
2194
tcp_server.clients[client_name] = Client.__new__(Client)
2195
for name, value in client.iteritems():
2196
setattr(tcp_server.clients[client_name], name, value)
2198
tcp_server.clients[client_name].decrypt_secret(
2199
client_settings[client_name]["secret"])
2201
# Create/remove clients based on new changes made to config
2202
for clientname in set(old_client_settings) - set(client_settings):
2203
del tcp_server.clients[clientname]
2204
for clientname in set(client_settings) - set(old_client_settings):
2205
tcp_server.clients[clientname] = (client_class(name = clientname,
2449
2211
if not tcp_server.clients:
2450
2212
logger.warning("No clients defined")
2537
2295
multiprocessing.active_children()
2538
2296
if not (tcp_server.clients or client_settings):
2541
# Store client before exiting. Secrets are encrypted with key
2542
# based on what config file has. If config file is
2543
# removed/edited, old secret will thus be unrecovable.
2545
with PGPEngine() as pgp:
2546
for client in tcp_server.clients.itervalues():
2547
key = client_settings[client.name]["secret"]
2548
client.encrypted_secret = pgp.encrypt(client.secret,
2552
# A list of attributes that can not be pickled
2554
exclude = set(("bus", "changedstate", "secret",
2556
for name, typ in (inspect.getmembers
2557
(dbus.service.Object)):
2560
client_dict["encrypted_secret"] = (client
2562
for attr in client.client_structure:
2563
if attr not in exclude:
2564
client_dict[attr] = getattr(client, attr)
2566
clients[client.name] = client_dict
2567
del client_settings[client.name]["secret"]
2299
# Store client before exiting. Secrets are encrypted with key based
2300
# on what config file has. If config file is removed/edited, old
2301
# secret will thus be unrecovable.
2303
for client in tcp_server.clients.itervalues():
2304
client.encrypt_secret(client_settings[client.name]["secret"])
2308
# A list of attributes that will not be stored when shuting down.
2309
exclude = set(("bus", "changedstate", "secret"))
2310
for name, typ in inspect.getmembers(dbus.service.Object):
2313
client_dict["encrypted_secret"] = client.encrypted_secret
2314
for attr in client.client_structure:
2315
if attr not in exclude:
2316
client_dict[attr] = getattr(client, attr)
2318
clients.append(client_dict)
2319
del client_settings[client.name]["secret"]
2570
with (tempfile.NamedTemporaryFile
2571
(mode='wb', suffix=".pickle", prefix='clients-',
2572
dir=os.path.dirname(stored_state_path),
2573
delete=False)) as stored_state:
2322
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2574
2323
pickle.dump((clients, client_settings), stored_state)
2575
tempname=stored_state.name
2576
os.rename(tempname, stored_state_path)
2577
except (IOError, OSError) as e:
2583
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2584
logger.warning("Could not save persistent state: {0}"
2585
.format(os.strerror(e.errno)))
2587
logger.warning("Could not save persistent state:",
2324
except IOError as e:
2325
logger.warning("Could not save persistant state: {0}".format(e))
2326
if e.errno != errno.ENOENT:
2591
2329
# Delete all clients, and settings from config
2592
2330
while tcp_server.clients:
2593
2331
name, client = tcp_server.clients.popitem()