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):
445
329
"created", "enabled", "fingerprint",
446
330
"host", "interval", "last_checked_ok",
447
331
"last_enabled", "name", "timeout")
448
client_defaults = { "timeout": "5m",
449
"extended_timeout": "15m",
451
"checker": "fping -q -- %%(host)s",
453
"approval_delay": "0s",
454
"approval_duration": "1s",
455
"approved_by_default": "True",
459
333
def timeout_milliseconds(self):
460
334
"Return the 'timeout' attribute in milliseconds"
461
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
463
337
def extended_timeout_milliseconds(self):
464
338
"Return the 'extended_timeout' attribute in milliseconds"
465
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
467
341
def interval_milliseconds(self):
468
342
"Return the 'interval' attribute in milliseconds"
469
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
471
345
def approval_delay_milliseconds(self):
472
return timedelta_to_milliseconds(self.approval_delay)
475
def config_parser(config):
476
"""Construct a new dict of client settings of this form:
477
{ client_name: {setting_name: value, ...}, ...}
478
with exceptions for any special settings as defined above.
479
NOTE: Must be a pure function. Must return the same result
480
value given the same arguments.
483
for client_name in config.sections():
484
section = dict(config.items(client_name))
485
client = settings[client_name] = {}
487
client["host"] = section["host"]
488
# Reformat values from string types to Python types
489
client["approved_by_default"] = config.getboolean(
490
client_name, "approved_by_default")
491
client["enabled"] = config.getboolean(client_name,
494
client["fingerprint"] = (section["fingerprint"].upper()
496
if "secret" in section:
497
client["secret"] = section["secret"].decode("base64")
498
elif "secfile" in section:
499
with open(os.path.expanduser(os.path.expandvars
500
(section["secfile"])),
502
client["secret"] = secfile.read()
504
raise TypeError("No secret or secfile for section {0}"
506
client["timeout"] = string_to_delta(section["timeout"])
507
client["extended_timeout"] = string_to_delta(
508
section["extended_timeout"])
509
client["interval"] = string_to_delta(section["interval"])
510
client["approval_delay"] = string_to_delta(
511
section["approval_delay"])
512
client["approval_duration"] = string_to_delta(
513
section["approval_duration"])
514
client["checker_command"] = section["checker"]
515
client["last_approval_request"] = None
516
client["last_checked_ok"] = None
517
client["last_checker_status"] = -2
521
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'
523
# adding all client settings
524
for setting, value in settings.iteritems():
525
setattr(self, setting, value)
528
if not hasattr(self, "last_enabled"):
529
self.last_enabled = datetime.datetime.utcnow()
530
if not hasattr(self, "expires"):
531
self.expires = (datetime.datetime.utcnow()
534
self.last_enabled = None
537
355
logger.debug("Creating client %r", self.name)
538
356
# Uppercase and remove spaces from fingerprint for later
539
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
541
361
logger.debug(" Fingerprint: %s", self.fingerprint)
542
self.created = settings.get("created",
543
datetime.datetime.utcnow())
545
# 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"])
546
383
self.checker = None
547
384
self.checker_initiator_tag = None
548
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
549
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
550
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
552
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"])
553
398
self.changedstate = (multiprocessing_manager
554
399
.Condition(multiprocessing_manager
556
self.client_structure = [attr for attr in
557
self.__dict__.iterkeys()
558
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
559
402
self.client_structure.append("client_structure")
561
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
565
407
if not name.startswith("_"):
566
408
self.client_structure.append(name)
575
417
if getattr(self, "enabled", False):
576
418
# Already enabled
420
self.send_changedstate()
578
421
self.expires = datetime.datetime.utcnow() + self.timeout
579
422
self.enabled = True
580
423
self.last_enabled = datetime.datetime.utcnow()
581
424
self.init_checker()
582
self.send_changedstate()
584
426
def disable(self, quiet=True):
585
427
"""Disable this client."""
586
428
if not getattr(self, "enabled", False):
431
self.send_changedstate()
589
433
logger.info("Disabling client %s", self.name)
590
if getattr(self, "disable_initiator_tag", None) is not None:
434
if getattr(self, "disable_initiator_tag", False):
591
435
gobject.source_remove(self.disable_initiator_tag)
592
436
self.disable_initiator_tag = None
593
437
self.expires = None
594
if getattr(self, "checker_initiator_tag", None) is not None:
438
if getattr(self, "checker_initiator_tag", False):
595
439
gobject.source_remove(self.checker_initiator_tag)
596
440
self.checker_initiator_tag = None
597
441
self.stop_checker()
598
442
self.enabled = False
600
self.send_changedstate()
601
443
# Do not run this again if called by a gobject.timeout_add
604
446
def __del__(self):
607
449
def init_checker(self):
608
450
# Schedule a new checker to be started an 'interval' from now,
609
451
# and every interval from then on.
610
if self.checker_initiator_tag is not None:
611
gobject.source_remove(self.checker_initiator_tag)
612
452
self.checker_initiator_tag = (gobject.timeout_add
613
453
(self.interval_milliseconds(),
614
454
self.start_checker))
615
455
# Schedule a disable() when 'timeout' has passed
616
if self.disable_initiator_tag is not None:
617
gobject.source_remove(self.disable_initiator_tag)
618
456
self.disable_initiator_tag = (gobject.timeout_add
619
457
(self.timeout_milliseconds(),
621
459
# Also start a new checker *right now*.
622
460
self.start_checker()
624
463
def checker_callback(self, pid, condition, command):
625
464
"""The checker has completed, so take appropriate actions."""
626
465
self.checker_callback_tag = None
627
466
self.checker = None
628
467
if os.WIFEXITED(condition):
629
self.last_checker_status = os.WEXITSTATUS(condition)
468
self.last_checker_status = os.WEXITSTATUS(condition)
630
469
if self.last_checker_status == 0:
631
470
logger.info("Checker for %(name)s succeeded",
746
583
logger.debug("Stopping checker for %(name)s", vars(self))
748
self.checker.terminate()
585
os.kill(self.checker.pid, signal.SIGTERM)
750
587
#if self.checker.poll() is None:
751
# self.checker.kill()
588
# os.kill(self.checker.pid, signal.SIGKILL)
752
589
except OSError as error:
753
590
if error.errno != errno.ESRCH: # No such process
755
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
758
641
def dbus_service_property(dbus_interface, signature="v",
759
642
access="readwrite", byte_arrays=False):
961
795
e.setAttribute("access", prop._dbus_access)
963
797
for if_tag in document.getElementsByTagName("interface"):
965
798
for tag in (make_tag(document, name, prop)
967
in self._get_all_dbus_things("property")
800
in self._get_all_dbus_properties()
968
801
if prop._dbus_interface
969
802
== if_tag.getAttribute("name")):
970
803
if_tag.appendChild(tag)
971
# Add annotation tags
972
for typ in ("method", "signal", "property"):
973
for tag in if_tag.getElementsByTagName(typ):
975
for name, prop in (self.
976
_get_all_dbus_things(typ)):
977
if (name == tag.getAttribute("name")
978
and prop._dbus_interface
979
== if_tag.getAttribute("name")):
980
annots.update(getattr
984
for name, value in annots.iteritems():
985
ann_tag = document.createElement(
987
ann_tag.setAttribute("name", name)
988
ann_tag.setAttribute("value", value)
989
tag.appendChild(ann_tag)
990
# Add interface annotation tags
991
for annotation, value in dict(
992
itertools.chain.from_iterable(
993
annotations().iteritems()
994
for name, annotations in
995
self._get_all_dbus_things("interface")
996
if name == if_tag.getAttribute("name")
998
ann_tag = document.createElement("annotation")
999
ann_tag.setAttribute("name", annotation)
1000
ann_tag.setAttribute("value", value)
1001
if_tag.appendChild(ann_tag)
1002
804
# Add the names to the return values for the
1003
805
# "org.freedesktop.DBus.Properties" methods
1004
806
if (if_tag.getAttribute("name")
1030
832
return dbus.String(dt.isoformat(),
1031
833
variant_level=variant_level)
1034
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1035
"""A class decorator; applied to a subclass of
1036
dbus.service.Object, it will add alternate D-Bus attributes with
1037
interface names according to the "alt_interface_names" mapping.
1040
@alternate_dbus_names({"org.example.Interface":
1041
"net.example.AlternateInterface"})
1042
class SampleDBusObject(dbus.service.Object):
1043
@dbus.service.method("org.example.Interface")
1044
def SampleDBusMethod():
1047
The above "SampleDBusMethod" on "SampleDBusObject" will be
1048
reachable via two interfaces: "org.example.Interface" and
1049
"net.example.AlternateInterface", the latter of which will have
1050
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1051
"true", unless "deprecate" is passed with a False value.
1053
This works for methods and signals, and also for D-Bus properties
1054
(from DBusObjectWithProperties) and interfaces (from the
1055
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.
1058
for orig_interface_name, alt_interface_name in (
1059
alt_interface_names.iteritems()):
1061
interface_names = set()
1062
# Go though all attributes of the class
1063
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):
1064
847
# Ignore non-D-Bus attributes, and D-Bus attributes
1065
848
# with the wrong interface name
1066
849
if (not hasattr(attribute, "_dbus_interface")
1067
850
or not attribute._dbus_interface
1068
.startswith(orig_interface_name)):
851
.startswith("se.recompile.Mandos")):
1070
853
# Create an alternate D-Bus interface name based on
1071
854
# the current name
1072
855
alt_interface = (attribute._dbus_interface
1073
.replace(orig_interface_name,
1074
alt_interface_name))
1075
interface_names.add(alt_interface)
856
.replace("se.recompile.Mandos",
857
"se.bsnet.fukt.Mandos"))
1076
858
# Is this a D-Bus signal?
1077
859
if getattr(attribute, "_dbus_is_signal", False):
1078
860
# Extract the original non-method function by
1157
927
attribute.func_name,
1158
928
attribute.func_defaults,
1159
929
attribute.func_closure)))
1160
# Copy annotations, if any
1162
attr[attrname]._dbus_annotations = (
1163
dict(attribute._dbus_annotations))
1164
except AttributeError:
1166
# Is this a D-Bus interface?
1167
elif getattr(attribute, "_dbus_is_interface", False):
1168
# Create a new, but exactly alike, function
1169
# object. Decorate it to be a new D-Bus interface
1170
# with the alternate D-Bus interface name. Add it
1172
attr[attrname] = (dbus_interface_annotations
1175
(attribute.func_code,
1176
attribute.func_globals,
1177
attribute.func_name,
1178
attribute.func_defaults,
1179
attribute.func_closure)))
1181
# Deprecate all alternate interfaces
1182
iname="_AlternateDBusNames_interface_annotation{0}"
1183
for interface_name in interface_names:
1184
@dbus_interface_annotations(interface_name)
1186
return { "org.freedesktop.DBus.Deprecated":
1188
# Find an unused name
1189
for aname in (iname.format(i)
1190
for i in itertools.count()):
1191
if aname not in attr:
1195
# Replace the class with a new subclass of it with
1196
# methods, signals, etc. as created above.
1197
cls = type(b"{0}Alternate".format(cls.__name__),
1203
@alternate_dbus_interfaces({"se.recompile.Mandos":
1204
"se.bsnet.fukt.Mandos"})
930
return type.__new__(mcs, name, bases, attr)
1205
932
class ClientDBus(Client, DBusObjectWithProperties):
1206
933
"""A Client class using D-Bus
1268
998
checker is not None)
1269
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1270
1000
"LastCheckedOK")
1271
last_checker_status = notifychangeproperty(dbus.Int16,
1272
"LastCheckerStatus")
1273
1001
last_approval_request = notifychangeproperty(
1274
1002
datetime_to_dbus, "LastApprovalRequest")
1275
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1276
1004
"ApprovedByDefault")
1277
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1278
1006
"ApprovalDelay",
1280
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1281
1009
approval_duration = notifychangeproperty(
1282
dbus.UInt64, "ApprovalDuration",
1283
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1284
1012
host = notifychangeproperty(dbus.String, "Host")
1285
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1287
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1288
1016
extended_timeout = notifychangeproperty(
1289
dbus.UInt64, "ExtendedTimeout",
1290
type_func = timedelta_to_milliseconds)
1291
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1294
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1295
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1297
1025
del notifychangeproperty
1537
1253
def Timeout_dbus_property(self, value=None):
1538
1254
if value is None: # get
1539
1255
return dbus.UInt64(self.timeout_milliseconds())
1540
old_timeout = self.timeout
1541
1256
self.timeout = datetime.timedelta(0, 0, 0, value)
1542
# Reschedule disabling
1544
now = datetime.datetime.utcnow()
1545
self.expires += self.timeout - old_timeout
1546
if self.expires <= now:
1547
# The timeout has passed
1550
if (getattr(self, "disable_initiator_tag", None)
1553
gobject.source_remove(self.disable_initiator_tag)
1554
self.disable_initiator_tag = (
1555
gobject.timeout_add(
1556
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))
1559
1278
# ExtendedTimeout - property
1560
1279
@dbus_service_property(_interface, signature="t",
2101
1830
elif suffix == "w":
2102
1831
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2104
raise ValueError("Unknown suffix {0!r}"
1833
raise ValueError("Unknown suffix %r" % suffix)
2106
1834
except (ValueError, IndexError) as e:
2107
1835
raise ValueError(*(e.args))
2108
1836
timevalue += delta
2109
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)
2112
1864
def daemon(nochdir = False, noclose = False):
2113
1865
"""See daemon(3). Standard BSD Unix function.
2236
1983
debuglevel = server_settings["debuglevel"]
2237
1984
use_dbus = server_settings["use_dbus"]
2238
1985
use_ipv6 = server_settings["use_ipv6"]
2239
stored_state_path = os.path.join(server_settings["statedir"],
2243
initlogger(debug, logging.DEBUG)
2248
level = getattr(logging, debuglevel.upper())
2249
initlogger(debug, level)
2251
1987
if server_settings["servicename"] != "Mandos":
2252
1988
syslogger.setFormatter(logging.Formatter
2253
('Mandos ({0}) [%(process)d]:'
2254
' %(levelname)s: %(message)s'
2255
.format(server_settings
1989
('Mandos (%s) [%%(process)d]:'
1990
' %%(levelname)s: %%(message)s'
1991
% server_settings["servicename"]))
2258
1993
# Parse config file with clients
2259
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)
2261
2003
client_config.read(os.path.join(server_settings["configdir"],
2262
2004
"clients.conf"))
2358
2111
client_class = Client
2360
client_class = functools.partial(ClientDBus, bus = bus)
2362
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())
2363
2133
old_client_settings = {}
2366
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2367
2137
if server_settings["restore"]:
2369
2139
with open(stored_state_path, "rb") as stored_state:
2370
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2372
2141
os.remove(stored_state_path)
2373
2142
except IOError as e:
2374
if e.errno == errno.ENOENT:
2375
logger.warning("Could not load persistent state: {0}"
2376
.format(os.strerror(e.errno)))
2378
logger.critical("Could not load persistent state:",
2143
logger.warning("Could not load persistant state: {0}".format(e))
2144
if e.errno != errno.ENOENT:
2381
except EOFError as e:
2382
logger.warning("Could not load persistent state: "
2383
"EOFError:", exc_info=e)
2385
with PGPEngine() as pgp:
2386
for client_name, client in clients_data.iteritems():
2387
# Decide which value to use after restoring saved state.
2388
# We have three different values: Old config file,
2389
# new config file, and saved state.
2390
# New config value takes precedence if it differs from old
2391
# config value, otherwise use saved state.
2392
for name, value in client_settings[client_name].items():
2394
# For each value in new config, check if it
2395
# differs from the old config value (Except for
2396
# the "secret" attribute)
2397
if (name != "secret" and
2398
value != old_client_settings[client_name]
2400
client[name] = value
2404
# Clients who has passed its expire date can still be
2405
# enabled if its last checker was successful. Clients
2406
# whose checker succeeded before we stored its state is
2407
# assumed to have successfully run all checkers during
2409
if client["enabled"]:
2410
if datetime.datetime.utcnow() >= client["expires"]:
2411
if not client["last_checked_ok"]:
2413
"disabling client {0} - Client never "
2414
"performed a successful checker"
2415
.format(client_name))
2416
client["enabled"] = False
2417
elif client["last_checker_status"] != 0:
2419
"disabling client {0} - Client "
2420
"last checker failed with error code {1}"
2421
.format(client_name,
2422
client["last_checker_status"]))
2423
client["enabled"] = False
2425
client["expires"] = (datetime.datetime
2427
+ client["timeout"])
2428
logger.debug("Last checker succeeded,"
2429
" keeping {0} enabled"
2430
.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():
2432
client["secret"] = (
2433
pgp.decrypt(client["encrypted_secret"],
2434
client_settings[client_name]
2437
# If decryption fails, we use secret from new settings
2438
logger.debug("Failed to decrypt {0} old secret"
2439
.format(client_name))
2440
client["secret"] = (
2441
client_settings[client_name]["secret"])
2443
# Add/remove clients based on new changes made to config
2444
for client_name in (set(old_client_settings)
2445
- set(client_settings)):
2446
del clients_data[client_name]
2447
for client_name in (set(client_settings)
2448
- set(old_client_settings)):
2449
clients_data[client_name] = client_settings[client_name]
2451
# Create all client objects
2452
for client_name, client in clients_data.iteritems():
2453
tcp_server.clients[client_name] = client_class(
2454
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,
2456
2211
if not tcp_server.clients:
2457
2212
logger.warning("No clients defined")
2545
2295
multiprocessing.active_children()
2546
2296
if not (tcp_server.clients or client_settings):
2549
# Store client before exiting. Secrets are encrypted with key
2550
# based on what config file has. If config file is
2551
# removed/edited, old secret will thus be unrecovable.
2553
with PGPEngine() as pgp:
2554
for client in tcp_server.clients.itervalues():
2555
key = client_settings[client.name]["secret"]
2556
client.encrypted_secret = pgp.encrypt(client.secret,
2560
# A list of attributes that can not be pickled
2562
exclude = set(("bus", "changedstate", "secret",
2564
for name, typ in (inspect.getmembers
2565
(dbus.service.Object)):
2568
client_dict["encrypted_secret"] = (client
2570
for attr in client.client_structure:
2571
if attr not in exclude:
2572
client_dict[attr] = getattr(client, attr)
2574
clients[client.name] = client_dict
2575
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"]
2578
with (tempfile.NamedTemporaryFile
2579
(mode='wb', suffix=".pickle", prefix='clients-',
2580
dir=os.path.dirname(stored_state_path),
2581
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:
2582
2323
pickle.dump((clients, client_settings), stored_state)
2583
tempname=stored_state.name
2584
os.rename(tempname, stored_state_path)
2585
except (IOError, OSError) as e:
2591
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2592
logger.warning("Could not save persistent state: {0}"
2593
.format(os.strerror(e.errno)))
2595
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:
2599
2329
# Delete all clients, and settings from config
2600
2330
while tcp_server.clients:
2601
2331
name, client = tcp_server.clients.popitem()