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):
442
329
"created", "enabled", "fingerprint",
443
330
"host", "interval", "last_checked_ok",
444
331
"last_enabled", "name", "timeout")
445
client_defaults = { "timeout": "5m",
446
"extended_timeout": "15m",
448
"checker": "fping -q -- %%(host)s",
450
"approval_delay": "0s",
451
"approval_duration": "1s",
452
"approved_by_default": "True",
456
333
def timeout_milliseconds(self):
457
334
"Return the 'timeout' attribute in milliseconds"
458
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
460
337
def extended_timeout_milliseconds(self):
461
338
"Return the 'extended_timeout' attribute in milliseconds"
462
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
464
341
def interval_milliseconds(self):
465
342
"Return the 'interval' attribute in milliseconds"
466
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
468
345
def approval_delay_milliseconds(self):
469
return timedelta_to_milliseconds(self.approval_delay)
472
def config_parser(config):
473
"""Construct a new dict of client settings of this form:
474
{ client_name: {setting_name: value, ...}, ...}
475
with exceptions for any special settings as defined above.
476
NOTE: Must be a pure function. Must return the same result
477
value given the same arguments.
480
for client_name in config.sections():
481
section = dict(config.items(client_name))
482
client = settings[client_name] = {}
484
client["host"] = section["host"]
485
# Reformat values from string types to Python types
486
client["approved_by_default"] = config.getboolean(
487
client_name, "approved_by_default")
488
client["enabled"] = config.getboolean(client_name,
491
client["fingerprint"] = (section["fingerprint"].upper()
493
if "secret" in section:
494
client["secret"] = section["secret"].decode("base64")
495
elif "secfile" in section:
496
with open(os.path.expanduser(os.path.expandvars
497
(section["secfile"])),
499
client["secret"] = secfile.read()
501
raise TypeError("No secret or secfile for section {0}"
503
client["timeout"] = string_to_delta(section["timeout"])
504
client["extended_timeout"] = string_to_delta(
505
section["extended_timeout"])
506
client["interval"] = string_to_delta(section["interval"])
507
client["approval_delay"] = string_to_delta(
508
section["approval_delay"])
509
client["approval_duration"] = string_to_delta(
510
section["approval_duration"])
511
client["checker_command"] = section["checker"]
512
client["last_approval_request"] = None
513
client["last_checked_ok"] = None
514
client["last_checker_status"] = -2
518
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'
520
# adding all client settings
521
for setting, value in settings.iteritems():
522
setattr(self, setting, value)
525
if not hasattr(self, "last_enabled"):
526
self.last_enabled = datetime.datetime.utcnow()
527
if not hasattr(self, "expires"):
528
self.expires = (datetime.datetime.utcnow()
531
self.last_enabled = None
534
355
logger.debug("Creating client %r", self.name)
535
356
# Uppercase and remove spaces from fingerprint for later
536
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
538
361
logger.debug(" Fingerprint: %s", self.fingerprint)
539
self.created = settings.get("created",
540
datetime.datetime.utcnow())
542
# 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"])
543
383
self.checker = None
544
384
self.checker_initiator_tag = None
545
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
546
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
547
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
549
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"])
550
398
self.changedstate = (multiprocessing_manager
551
399
.Condition(multiprocessing_manager
553
self.client_structure = [attr for attr in
554
self.__dict__.iterkeys()
555
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
556
402
self.client_structure.append("client_structure")
558
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
562
407
if not name.startswith("_"):
563
408
self.client_structure.append(name)
572
417
if getattr(self, "enabled", False):
573
418
# Already enabled
420
self.send_changedstate()
575
421
self.expires = datetime.datetime.utcnow() + self.timeout
576
422
self.enabled = True
577
423
self.last_enabled = datetime.datetime.utcnow()
578
424
self.init_checker()
579
self.send_changedstate()
581
426
def disable(self, quiet=True):
582
427
"""Disable this client."""
583
428
if not getattr(self, "enabled", False):
431
self.send_changedstate()
586
433
logger.info("Disabling client %s", self.name)
587
if getattr(self, "disable_initiator_tag", None) is not None:
434
if getattr(self, "disable_initiator_tag", False):
588
435
gobject.source_remove(self.disable_initiator_tag)
589
436
self.disable_initiator_tag = None
590
437
self.expires = None
591
if getattr(self, "checker_initiator_tag", None) is not None:
438
if getattr(self, "checker_initiator_tag", False):
592
439
gobject.source_remove(self.checker_initiator_tag)
593
440
self.checker_initiator_tag = None
594
441
self.stop_checker()
595
442
self.enabled = False
597
self.send_changedstate()
598
443
# Do not run this again if called by a gobject.timeout_add
601
446
def __del__(self):
604
449
def init_checker(self):
605
450
# Schedule a new checker to be started an 'interval' from now,
606
451
# and every interval from then on.
607
if self.checker_initiator_tag is not None:
608
gobject.source_remove(self.checker_initiator_tag)
609
452
self.checker_initiator_tag = (gobject.timeout_add
610
453
(self.interval_milliseconds(),
611
454
self.start_checker))
612
455
# Schedule a disable() when 'timeout' has passed
613
if self.disable_initiator_tag is not None:
614
gobject.source_remove(self.disable_initiator_tag)
615
456
self.disable_initiator_tag = (gobject.timeout_add
616
457
(self.timeout_milliseconds(),
618
459
# Also start a new checker *right now*.
619
460
self.start_checker()
621
463
def checker_callback(self, pid, condition, command):
622
464
"""The checker has completed, so take appropriate actions."""
623
465
self.checker_callback_tag = None
624
466
self.checker = None
625
467
if os.WIFEXITED(condition):
626
self.last_checker_status = os.WEXITSTATUS(condition)
468
self.last_checker_status = os.WEXITSTATUS(condition)
627
469
if self.last_checker_status == 0:
628
470
logger.info("Checker for %(name)s succeeded",
743
583
logger.debug("Stopping checker for %(name)s", vars(self))
745
self.checker.terminate()
585
os.kill(self.checker.pid, signal.SIGTERM)
747
587
#if self.checker.poll() is None:
748
# self.checker.kill()
588
# os.kill(self.checker.pid, signal.SIGKILL)
749
589
except OSError as error:
750
590
if error.errno != errno.ESRCH: # No such process
752
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
755
641
def dbus_service_property(dbus_interface, signature="v",
756
642
access="readwrite", byte_arrays=False):
958
795
e.setAttribute("access", prop._dbus_access)
960
797
for if_tag in document.getElementsByTagName("interface"):
962
798
for tag in (make_tag(document, name, prop)
964
in self._get_all_dbus_things("property")
800
in self._get_all_dbus_properties()
965
801
if prop._dbus_interface
966
802
== if_tag.getAttribute("name")):
967
803
if_tag.appendChild(tag)
968
# Add annotation tags
969
for typ in ("method", "signal", "property"):
970
for tag in if_tag.getElementsByTagName(typ):
972
for name, prop in (self.
973
_get_all_dbus_things(typ)):
974
if (name == tag.getAttribute("name")
975
and prop._dbus_interface
976
== if_tag.getAttribute("name")):
977
annots.update(getattr
981
for name, value in annots.iteritems():
982
ann_tag = document.createElement(
984
ann_tag.setAttribute("name", name)
985
ann_tag.setAttribute("value", value)
986
tag.appendChild(ann_tag)
987
# Add interface annotation tags
988
for annotation, value in dict(
989
itertools.chain.from_iterable(
990
annotations().iteritems()
991
for name, annotations in
992
self._get_all_dbus_things("interface")
993
if name == if_tag.getAttribute("name")
995
ann_tag = document.createElement("annotation")
996
ann_tag.setAttribute("name", annotation)
997
ann_tag.setAttribute("value", value)
998
if_tag.appendChild(ann_tag)
999
804
# Add the names to the return values for the
1000
805
# "org.freedesktop.DBus.Properties" methods
1001
806
if (if_tag.getAttribute("name")
1027
832
return dbus.String(dt.isoformat(),
1028
833
variant_level=variant_level)
1031
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1032
"""A class decorator; applied to a subclass of
1033
dbus.service.Object, it will add alternate D-Bus attributes with
1034
interface names according to the "alt_interface_names" mapping.
1037
@alternate_dbus_names({"org.example.Interface":
1038
"net.example.AlternateInterface"})
1039
class SampleDBusObject(dbus.service.Object):
1040
@dbus.service.method("org.example.Interface")
1041
def SampleDBusMethod():
1044
The above "SampleDBusMethod" on "SampleDBusObject" will be
1045
reachable via two interfaces: "org.example.Interface" and
1046
"net.example.AlternateInterface", the latter of which will have
1047
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1048
"true", unless "deprecate" is passed with a False value.
1050
This works for methods and signals, and also for D-Bus properties
1051
(from DBusObjectWithProperties) and interfaces (from the
1052
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.
1055
for orig_interface_name, alt_interface_name in (
1056
alt_interface_names.iteritems()):
1058
interface_names = set()
1059
# Go though all attributes of the class
1060
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):
1061
847
# Ignore non-D-Bus attributes, and D-Bus attributes
1062
848
# with the wrong interface name
1063
849
if (not hasattr(attribute, "_dbus_interface")
1064
850
or not attribute._dbus_interface
1065
.startswith(orig_interface_name)):
851
.startswith("se.recompile.Mandos")):
1067
853
# Create an alternate D-Bus interface name based on
1068
854
# the current name
1069
855
alt_interface = (attribute._dbus_interface
1070
.replace(orig_interface_name,
1071
alt_interface_name))
1072
interface_names.add(alt_interface)
856
.replace("se.recompile.Mandos",
857
"se.bsnet.fukt.Mandos"))
1073
858
# Is this a D-Bus signal?
1074
859
if getattr(attribute, "_dbus_is_signal", False):
1075
860
# Extract the original non-method function by
1154
927
attribute.func_name,
1155
928
attribute.func_defaults,
1156
929
attribute.func_closure)))
1157
# Copy annotations, if any
1159
attr[attrname]._dbus_annotations = (
1160
dict(attribute._dbus_annotations))
1161
except AttributeError:
1163
# Is this a D-Bus interface?
1164
elif getattr(attribute, "_dbus_is_interface", False):
1165
# Create a new, but exactly alike, function
1166
# object. Decorate it to be a new D-Bus interface
1167
# with the alternate D-Bus interface name. Add it
1169
attr[attrname] = (dbus_interface_annotations
1172
(attribute.func_code,
1173
attribute.func_globals,
1174
attribute.func_name,
1175
attribute.func_defaults,
1176
attribute.func_closure)))
1178
# Deprecate all alternate interfaces
1179
iname="_AlternateDBusNames_interface_annotation{0}"
1180
for interface_name in interface_names:
1181
@dbus_interface_annotations(interface_name)
1183
return { "org.freedesktop.DBus.Deprecated":
1185
# Find an unused name
1186
for aname in (iname.format(i)
1187
for i in itertools.count()):
1188
if aname not in attr:
1192
# Replace the class with a new subclass of it with
1193
# methods, signals, etc. as created above.
1194
cls = type(b"{0}Alternate".format(cls.__name__),
1200
@alternate_dbus_interfaces({"se.recompile.Mandos":
1201
"se.bsnet.fukt.Mandos"})
930
return type.__new__(mcs, name, bases, attr)
1202
932
class ClientDBus(Client, DBusObjectWithProperties):
1203
933
"""A Client class using D-Bus
1265
998
checker is not None)
1266
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1267
1000
"LastCheckedOK")
1268
last_checker_status = notifychangeproperty(dbus.Int16,
1269
"LastCheckerStatus")
1270
1001
last_approval_request = notifychangeproperty(
1271
1002
datetime_to_dbus, "LastApprovalRequest")
1272
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1273
1004
"ApprovedByDefault")
1274
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1275
1006
"ApprovalDelay",
1277
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1278
1009
approval_duration = notifychangeproperty(
1279
dbus.UInt64, "ApprovalDuration",
1280
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1281
1012
host = notifychangeproperty(dbus.String, "Host")
1282
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1284
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1285
1016
extended_timeout = notifychangeproperty(
1286
dbus.UInt64, "ExtendedTimeout",
1287
type_func = timedelta_to_milliseconds)
1288
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1291
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1292
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1294
1025
del notifychangeproperty
1534
1253
def Timeout_dbus_property(self, value=None):
1535
1254
if value is None: # get
1536
1255
return dbus.UInt64(self.timeout_milliseconds())
1537
old_timeout = self.timeout
1538
1256
self.timeout = datetime.timedelta(0, 0, 0, value)
1539
# Reschedule disabling
1541
now = datetime.datetime.utcnow()
1542
self.expires += self.timeout - old_timeout
1543
if self.expires <= now:
1544
# The timeout has passed
1547
if (getattr(self, "disable_initiator_tag", None)
1550
gobject.source_remove(self.disable_initiator_tag)
1551
self.disable_initiator_tag = (
1552
gobject.timeout_add(
1553
timedelta_to_milliseconds(self.expires - now),
1257
if getattr(self, "disable_initiator_tag", None) is None:
1259
# Reschedule timeout
1260
gobject.source_remove(self.disable_initiator_tag)
1261
self.disable_initiator_tag = None
1263
time_to_die = _timedelta_to_milliseconds((self
1268
if time_to_die <= 0:
1269
# The timeout has passed
1272
self.expires = (datetime.datetime.utcnow()
1273
+ datetime.timedelta(milliseconds =
1275
self.disable_initiator_tag = (gobject.timeout_add
1276
(time_to_die, self.disable))
1556
1278
# ExtendedTimeout - property
1557
1279
@dbus_service_property(_interface, signature="t",
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.
2229
1983
debuglevel = server_settings["debuglevel"]
2230
1984
use_dbus = server_settings["use_dbus"]
2231
1985
use_ipv6 = server_settings["use_ipv6"]
2232
stored_state_path = os.path.join(server_settings["statedir"],
2236
initlogger(debug, logging.DEBUG)
2241
level = getattr(logging, debuglevel.upper())
2242
initlogger(debug, level)
2244
1987
if server_settings["servicename"] != "Mandos":
2245
1988
syslogger.setFormatter(logging.Formatter
2246
('Mandos ({0}) [%(process)d]:'
2247
' %(levelname)s: %(message)s'
2248
.format(server_settings
1989
('Mandos (%s) [%%(process)d]:'
1990
' %%(levelname)s: %%(message)s'
1991
% server_settings["servicename"]))
2251
1993
# Parse config file with clients
2252
client_config = configparser.SafeConfigParser(Client
1994
client_defaults = { "timeout": "5m",
1995
"extended_timeout": "15m",
1997
"checker": "fping -q -- %%(host)s",
1999
"approval_delay": "0s",
2000
"approval_duration": "1s",
2002
client_config = configparser.SafeConfigParser(client_defaults)
2254
2003
client_config.read(os.path.join(server_settings["configdir"],
2255
2004
"clients.conf"))
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")
2538
2295
multiprocessing.active_children()
2539
2296
if not (tcp_server.clients or client_settings):
2542
# Store client before exiting. Secrets are encrypted with key
2543
# based on what config file has. If config file is
2544
# removed/edited, old secret will thus be unrecovable.
2546
with PGPEngine() as pgp:
2547
for client in tcp_server.clients.itervalues():
2548
key = client_settings[client.name]["secret"]
2549
client.encrypted_secret = pgp.encrypt(client.secret,
2553
# A list of attributes that can not be pickled
2555
exclude = set(("bus", "changedstate", "secret",
2557
for name, typ in (inspect.getmembers
2558
(dbus.service.Object)):
2561
client_dict["encrypted_secret"] = (client
2563
for attr in client.client_structure:
2564
if attr not in exclude:
2565
client_dict[attr] = getattr(client, attr)
2567
clients[client.name] = client_dict
2568
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"]
2571
with (tempfile.NamedTemporaryFile
2572
(mode='wb', suffix=".pickle", prefix='clients-',
2573
dir=os.path.dirname(stored_state_path),
2574
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:
2575
2323
pickle.dump((clients, client_settings), stored_state)
2576
tempname=stored_state.name
2577
os.rename(tempname, stored_state_path)
2578
except (IOError, OSError) as e:
2584
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2585
logger.warning("Could not save persistent state: {0}"
2586
.format(os.strerror(e.errno)))
2588
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:
2592
2329
# Delete all clients, and settings from config
2593
2330
while tcp_server.clients:
2594
2331
name, client = tcp_server.clients.popitem()