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.tempdir = tempfile.mkdtemp(prefix="mandos-")
143
self.gnupgargs = ['--batch',
144
'--home', self.tempdir,
152
def __exit__(self, exc_type, exc_value, traceback):
160
if self.tempdir is not None:
161
# Delete contents of tempdir
162
for root, dirs, files in os.walk(self.tempdir,
164
for filename in files:
165
os.remove(os.path.join(root, filename))
167
os.rmdir(os.path.join(root, dirname))
169
os.rmdir(self.tempdir)
172
def password_encode(self, password):
173
# Passphrase can not be empty and can not contain newlines or
174
# NUL bytes. So we prefix it and hex encode it.
175
encoded = b"mandos" + binascii.hexlify(password)
176
if len(encoded) > 2048:
177
# GnuPG can't handle long passwords, so encode differently
178
encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
179
.replace(b"\n", b"\\n")
180
.replace(b"\0", b"\\x00"))
183
def encrypt(self, data, password):
184
passphrase = self.password_encode(password)
185
with tempfile.NamedTemporaryFile(dir=self.tempdir
187
passfile.write(passphrase)
189
proc = subprocess.Popen(['gpg', '--symmetric',
193
stdin = subprocess.PIPE,
194
stdout = subprocess.PIPE,
195
stderr = subprocess.PIPE)
196
ciphertext, err = proc.communicate(input = data)
197
if proc.returncode != 0:
201
def decrypt(self, data, password):
202
passphrase = self.password_encode(password)
203
with tempfile.NamedTemporaryFile(dir = self.tempdir
205
passfile.write(passphrase)
207
proc = subprocess.Popen(['gpg', '--decrypt',
211
stdin = subprocess.PIPE,
212
stdout = subprocess.PIPE,
213
stderr = subprocess.PIPE)
214
decrypted_plaintext, err = proc.communicate(input
216
if proc.returncode != 0:
218
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)
221
109
class AvahiError(Exception):
433
310
interval: datetime.timedelta(); How often to start a new checker
434
311
last_approval_request: datetime.datetime(); (UTC) or None
435
312
last_checked_ok: datetime.datetime(); (UTC) or None
436
last_checker_status: integer between 0 and 255 reflecting exit
437
status of last checker. -1 reflects crashed
438
checker, -2 means no checker completed yet.
439
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)
440
317
name: string; from the config file, used in log messages and
441
318
D-Bus identifiers
442
319
secret: bytestring; sent verbatim (over TLS) to client
443
320
timeout: datetime.timedelta(); How long from last_checked_ok
444
321
until this client is disabled
445
extended_timeout: extra long timeout when secret has been sent
322
extended_timeout: extra long timeout when password has been sent
446
323
runtime_expansions: Allowed attributes for runtime expansion.
447
324
expires: datetime.datetime(); time (UTC) when a client will be
448
325
disabled, or None
449
server_settings: The server_settings dict from main()
452
328
runtime_expansions = ("approval_delay", "approval_duration",
453
"created", "enabled", "expires",
454
"fingerprint", "host", "interval",
455
"last_approval_request", "last_checked_ok",
329
"created", "enabled", "fingerprint",
330
"host", "interval", "last_checked_ok",
456
331
"last_enabled", "name", "timeout")
457
client_defaults = { "timeout": "PT5M",
458
"extended_timeout": "PT15M",
460
"checker": "fping -q -- %%(host)s",
462
"approval_delay": "PT0S",
463
"approval_duration": "PT1S",
464
"approved_by_default": "True",
468
333
def timeout_milliseconds(self):
469
334
"Return the 'timeout' attribute in milliseconds"
470
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
472
337
def extended_timeout_milliseconds(self):
473
338
"Return the 'extended_timeout' attribute in milliseconds"
474
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
476
341
def interval_milliseconds(self):
477
342
"Return the 'interval' attribute in milliseconds"
478
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
480
345
def approval_delay_milliseconds(self):
481
return timedelta_to_milliseconds(self.approval_delay)
484
def config_parser(config):
485
"""Construct a new dict of client settings of this form:
486
{ client_name: {setting_name: value, ...}, ...}
487
with exceptions for any special settings as defined above.
488
NOTE: Must be a pure function. Must return the same result
489
value given the same arguments.
492
for client_name in config.sections():
493
section = dict(config.items(client_name))
494
client = settings[client_name] = {}
496
client["host"] = section["host"]
497
# Reformat values from string types to Python types
498
client["approved_by_default"] = config.getboolean(
499
client_name, "approved_by_default")
500
client["enabled"] = config.getboolean(client_name,
503
client["fingerprint"] = (section["fingerprint"].upper()
505
if "secret" in section:
506
client["secret"] = section["secret"].decode("base64")
507
elif "secfile" in section:
508
with open(os.path.expanduser(os.path.expandvars
509
(section["secfile"])),
511
client["secret"] = secfile.read()
513
raise TypeError("No secret or secfile for section {0}"
515
client["timeout"] = string_to_delta(section["timeout"])
516
client["extended_timeout"] = string_to_delta(
517
section["extended_timeout"])
518
client["interval"] = string_to_delta(section["interval"])
519
client["approval_delay"] = string_to_delta(
520
section["approval_delay"])
521
client["approval_duration"] = string_to_delta(
522
section["approval_duration"])
523
client["checker_command"] = section["checker"]
524
client["last_approval_request"] = None
525
client["last_checked_ok"] = None
526
client["last_checker_status"] = -2
530
def __init__(self, settings, name = None, server_settings=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'
532
if server_settings is None:
534
self.server_settings = server_settings
535
# adding all client settings
536
for setting, value in settings.iteritems():
537
setattr(self, setting, value)
540
if not hasattr(self, "last_enabled"):
541
self.last_enabled = datetime.datetime.utcnow()
542
if not hasattr(self, "expires"):
543
self.expires = (datetime.datetime.utcnow()
546
self.last_enabled = None
549
355
logger.debug("Creating client %r", self.name)
550
356
# Uppercase and remove spaces from fingerprint for later
551
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
553
361
logger.debug(" Fingerprint: %s", self.fingerprint)
554
self.created = settings.get("created",
555
datetime.datetime.utcnow())
557
# 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"])
558
383
self.checker = None
559
384
self.checker_initiator_tag = None
560
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
561
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
562
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
564
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"])
565
398
self.changedstate = (multiprocessing_manager
566
399
.Condition(multiprocessing_manager
568
self.client_structure = [attr for attr in
569
self.__dict__.iterkeys()
570
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
571
402
self.client_structure.append("client_structure")
573
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
577
407
if not name.startswith("_"):
578
408
self.client_structure.append(name)
587
417
if getattr(self, "enabled", False):
588
418
# Already enabled
420
self.send_changedstate()
590
421
self.expires = datetime.datetime.utcnow() + self.timeout
591
422
self.enabled = True
592
423
self.last_enabled = datetime.datetime.utcnow()
593
424
self.init_checker()
594
self.send_changedstate()
596
426
def disable(self, quiet=True):
597
427
"""Disable this client."""
598
428
if not getattr(self, "enabled", False):
431
self.send_changedstate()
601
433
logger.info("Disabling client %s", self.name)
602
if getattr(self, "disable_initiator_tag", None) is not None:
434
if getattr(self, "disable_initiator_tag", False):
603
435
gobject.source_remove(self.disable_initiator_tag)
604
436
self.disable_initiator_tag = None
605
437
self.expires = None
606
if getattr(self, "checker_initiator_tag", None) is not None:
438
if getattr(self, "checker_initiator_tag", False):
607
439
gobject.source_remove(self.checker_initiator_tag)
608
440
self.checker_initiator_tag = None
609
441
self.stop_checker()
610
442
self.enabled = False
612
self.send_changedstate()
613
443
# Do not run this again if called by a gobject.timeout_add
616
446
def __del__(self):
619
449
def init_checker(self):
620
450
# Schedule a new checker to be started an 'interval' from now,
621
451
# and every interval from then on.
622
if self.checker_initiator_tag is not None:
623
gobject.source_remove(self.checker_initiator_tag)
624
452
self.checker_initiator_tag = (gobject.timeout_add
625
453
(self.interval_milliseconds(),
626
454
self.start_checker))
627
455
# Schedule a disable() when 'timeout' has passed
628
if self.disable_initiator_tag is not None:
629
gobject.source_remove(self.disable_initiator_tag)
630
456
self.disable_initiator_tag = (gobject.timeout_add
631
457
(self.timeout_milliseconds(),
633
459
# Also start a new checker *right now*.
634
460
self.start_checker()
636
463
def checker_callback(self, pid, condition, command):
637
464
"""The checker has completed, so take appropriate actions."""
638
465
self.checker_callback_tag = None
639
466
self.checker = None
640
467
if os.WIFEXITED(condition):
641
self.last_checker_status = os.WEXITSTATUS(condition)
468
self.last_checker_status = os.WEXITSTATUS(condition)
642
469
if self.last_checker_status == 0:
643
470
logger.info("Checker for %(name)s succeeded",
722
554
# in normal mode, that is already done by daemon(),
723
555
# and in debug mode we don't want to. (Stdin is
724
556
# always replaced by /dev/null.)
725
# The exception is when not debugging but nevertheless
726
# running in the foreground; use the previously
729
if (not self.server_settings["debug"]
730
and self.server_settings["foreground"]):
731
popen_args.update({"stdout": wnull,
733
557
self.checker = subprocess.Popen(command,
737
except OSError as error:
738
logger.error("Failed to start subprocess",
741
self.checker_callback_tag = (gobject.child_watch_add
743
self.checker_callback,
745
# The checker may have completed before the gobject
746
# watch was added. Check for this.
560
self.checker_callback_tag = (gobject.child_watch_add
562
self.checker_callback,
564
# The checker may have completed before the gobject
565
# watch was added. Check for this.
748
566
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
568
gobject.source_remove(self.checker_callback_tag)
569
self.checker_callback(pid, status, command)
749
570
except OSError as error:
750
if error.errno == errno.ECHILD:
751
# This should never happen
752
logger.error("Child process vanished",
757
gobject.source_remove(self.checker_callback_tag)
758
self.checker_callback(pid, status, command)
571
logger.error("Failed to start subprocess: %s",
759
573
# Re-run this periodically if run by gobject.timeout_add
769
583
logger.debug("Stopping checker for %(name)s", vars(self))
771
self.checker.terminate()
585
os.kill(self.checker.pid, signal.SIGTERM)
773
587
#if self.checker.poll() is None:
774
# self.checker.kill()
588
# os.kill(self.checker.pid, signal.SIGKILL)
775
589
except OSError as error:
776
590
if error.errno != errno.ESRCH: # No such process
778
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
781
641
def dbus_service_property(dbus_interface, signature="v",
782
642
access="readwrite", byte_arrays=False):
986
795
e.setAttribute("access", prop._dbus_access)
988
797
for if_tag in document.getElementsByTagName("interface"):
990
798
for tag in (make_tag(document, name, prop)
992
in self._get_all_dbus_things("property")
800
in self._get_all_dbus_properties()
993
801
if prop._dbus_interface
994
802
== if_tag.getAttribute("name")):
995
803
if_tag.appendChild(tag)
996
# Add annotation tags
997
for typ in ("method", "signal", "property"):
998
for tag in if_tag.getElementsByTagName(typ):
1000
for name, prop in (self.
1001
_get_all_dbus_things(typ)):
1002
if (name == tag.getAttribute("name")
1003
and prop._dbus_interface
1004
== if_tag.getAttribute("name")):
1005
annots.update(getattr
1007
"_dbus_annotations",
1009
for name, value in annots.iteritems():
1010
ann_tag = document.createElement(
1012
ann_tag.setAttribute("name", name)
1013
ann_tag.setAttribute("value", value)
1014
tag.appendChild(ann_tag)
1015
# Add interface annotation tags
1016
for annotation, value in dict(
1017
itertools.chain.from_iterable(
1018
annotations().iteritems()
1019
for name, annotations in
1020
self._get_all_dbus_things("interface")
1021
if name == if_tag.getAttribute("name")
1023
ann_tag = document.createElement("annotation")
1024
ann_tag.setAttribute("name", annotation)
1025
ann_tag.setAttribute("value", value)
1026
if_tag.appendChild(ann_tag)
1027
804
# Add the names to the return values for the
1028
805
# "org.freedesktop.DBus.Properties" methods
1029
806
if (if_tag.getAttribute("name")
1044
821
except (AttributeError, xml.dom.DOMException,
1045
822
xml.parsers.expat.ExpatError) as error:
1046
823
logger.error("Failed to override Introspection method",
1048
825
return xmlstring
1051
def datetime_to_dbus(dt, variant_level=0):
828
def datetime_to_dbus (dt, variant_level=0):
1052
829
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1054
831
return dbus.String("", variant_level = variant_level)
1055
832
return dbus.String(dt.isoformat(),
1056
833
variant_level=variant_level)
1059
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1060
"""A class decorator; applied to a subclass of
1061
dbus.service.Object, it will add alternate D-Bus attributes with
1062
interface names according to the "alt_interface_names" mapping.
1065
@alternate_dbus_interfaces({"org.example.Interface":
1066
"net.example.AlternateInterface"})
1067
class SampleDBusObject(dbus.service.Object):
1068
@dbus.service.method("org.example.Interface")
1069
def SampleDBusMethod():
1072
The above "SampleDBusMethod" on "SampleDBusObject" will be
1073
reachable via two interfaces: "org.example.Interface" and
1074
"net.example.AlternateInterface", the latter of which will have
1075
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1076
"true", unless "deprecate" is passed with a False value.
1078
This works for methods and signals, and also for D-Bus properties
1079
(from DBusObjectWithProperties) and interfaces (from the
1080
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.
1083
for orig_interface_name, alt_interface_name in (
1084
alt_interface_names.iteritems()):
1086
interface_names = set()
1087
# Go though all attributes of the class
1088
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):
1089
847
# Ignore non-D-Bus attributes, and D-Bus attributes
1090
848
# with the wrong interface name
1091
849
if (not hasattr(attribute, "_dbus_interface")
1092
850
or not attribute._dbus_interface
1093
.startswith(orig_interface_name)):
851
.startswith("se.recompile.Mandos")):
1095
853
# Create an alternate D-Bus interface name based on
1096
854
# the current name
1097
855
alt_interface = (attribute._dbus_interface
1098
.replace(orig_interface_name,
1099
alt_interface_name))
1100
interface_names.add(alt_interface)
856
.replace("se.recompile.Mandos",
857
"se.bsnet.fukt.Mandos"))
1101
858
# Is this a D-Bus signal?
1102
859
if getattr(attribute, "_dbus_is_signal", False):
1103
# Extract the original non-method undecorated
1104
# function by black magic
860
# Extract the original non-method function by
1105
862
nonmethod_func = (dict(
1106
863
zip(attribute.func_code.co_freevars,
1107
864
attribute.__closure__))["func"]
1182
927
attribute.func_name,
1183
928
attribute.func_defaults,
1184
929
attribute.func_closure)))
1185
# Copy annotations, if any
1187
attr[attrname]._dbus_annotations = (
1188
dict(attribute._dbus_annotations))
1189
except AttributeError:
1191
# Is this a D-Bus interface?
1192
elif getattr(attribute, "_dbus_is_interface", False):
1193
# Create a new, but exactly alike, function
1194
# object. Decorate it to be a new D-Bus interface
1195
# with the alternate D-Bus interface name. Add it
1197
attr[attrname] = (dbus_interface_annotations
1200
(attribute.func_code,
1201
attribute.func_globals,
1202
attribute.func_name,
1203
attribute.func_defaults,
1204
attribute.func_closure)))
1206
# Deprecate all alternate interfaces
1207
iname="_AlternateDBusNames_interface_annotation{0}"
1208
for interface_name in interface_names:
1209
@dbus_interface_annotations(interface_name)
1211
return { "org.freedesktop.DBus.Deprecated":
1213
# Find an unused name
1214
for aname in (iname.format(i)
1215
for i in itertools.count()):
1216
if aname not in attr:
1220
# Replace the class with a new subclass of it with
1221
# methods, signals, etc. as created above.
1222
cls = type(b"{0}Alternate".format(cls.__name__),
1228
@alternate_dbus_interfaces({"se.recompile.Mandos":
1229
"se.bsnet.fukt.Mandos"})
930
return type.__new__(mcs, name, bases, attr)
1230
932
class ClientDBus(Client, DBusObjectWithProperties):
1231
933
"""A Client class using D-Bus
1293
998
checker is not None)
1294
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1295
1000
"LastCheckedOK")
1296
last_checker_status = notifychangeproperty(dbus.Int16,
1297
"LastCheckerStatus")
1298
1001
last_approval_request = notifychangeproperty(
1299
1002
datetime_to_dbus, "LastApprovalRequest")
1300
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1301
1004
"ApprovedByDefault")
1302
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1303
1006
"ApprovalDelay",
1305
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1306
1009
approval_duration = notifychangeproperty(
1307
dbus.UInt64, "ApprovalDuration",
1308
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1309
1012
host = notifychangeproperty(dbus.String, "Host")
1310
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1312
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1313
1016
extended_timeout = notifychangeproperty(
1314
dbus.UInt64, "ExtendedTimeout",
1315
type_func = timedelta_to_milliseconds)
1316
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1319
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1320
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1322
1025
del notifychangeproperty
1931
1625
use_ipv6: Boolean; to use IPv6 or not
1933
1627
def __init__(self, server_address, RequestHandlerClass,
1934
interface=None, use_ipv6=True, socketfd=None):
1935
"""If socketfd is set, use that file descriptor instead of
1936
creating a new one with socket.socket().
1628
interface=None, use_ipv6=True):
1938
1629
self.interface = interface
1940
1631
self.address_family = socket.AF_INET6
1941
if socketfd is not None:
1942
# Save the file descriptor
1943
self.socketfd = socketfd
1944
# Save the original socket.socket() function
1945
self.socket_socket = socket.socket
1946
# To implement --socket, we monkey patch socket.socket.
1948
# (When socketserver.TCPServer is a new-style class, we
1949
# could make self.socket into a property instead of monkey
1950
# patching socket.socket.)
1952
# Create a one-time-only replacement for socket.socket()
1953
@functools.wraps(socket.socket)
1954
def socket_wrapper(*args, **kwargs):
1955
# Restore original function so subsequent calls are
1957
socket.socket = self.socket_socket
1958
del self.socket_socket
1959
# This time only, return a new socket object from the
1960
# saved file descriptor.
1961
return socket.fromfd(self.socketfd, *args, **kwargs)
1962
# Replace socket.socket() function with wrapper
1963
socket.socket = socket_wrapper
1964
# The socketserver.TCPServer.__init__ will call
1965
# socket.socket(), which might be our replacement,
1966
# socket_wrapper(), if socketfd was set.
1967
1632
socketserver.TCPServer.__init__(self, server_address,
1968
1633
RequestHandlerClass)
1970
1634
def server_bind(self):
1971
1635
"""This overrides the normal server_bind() function
1972
1636
to bind to an interface if one was specified, and also NOT to
2125
def rfc3339_duration_to_delta(duration):
2126
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2128
>>> rfc3339_duration_to_delta("P7D")
2129
datetime.timedelta(7)
2130
>>> rfc3339_duration_to_delta("PT60S")
2131
datetime.timedelta(0, 60)
2132
>>> rfc3339_duration_to_delta("PT60M")
2133
datetime.timedelta(0, 3600)
2134
>>> rfc3339_duration_to_delta("PT24H")
2135
datetime.timedelta(1)
2136
>>> rfc3339_duration_to_delta("P1W")
2137
datetime.timedelta(7)
2138
>>> rfc3339_duration_to_delta("PT5M30S")
2139
datetime.timedelta(0, 330)
2140
>>> rfc3339_duration_to_delta("P1DT3M20S")
2141
datetime.timedelta(1, 200)
2144
# Parsing an RFC 3339 duration with regular expressions is not
2145
# possible - there would have to be multiple places for the same
2146
# values, like seconds. The current code, while more esoteric, is
2147
# cleaner without depending on a parsing library. If Python had a
2148
# built-in library for parsing we would use it, but we'd like to
2149
# avoid excessive use of external libraries.
2151
# New type for defining tokens, syntax, and semantics all-in-one
2152
Token = collections.namedtuple("Token",
2153
("regexp", # To match token; if
2154
# "value" is not None,
2155
# must have a "group"
2157
"value", # datetime.timedelta or
2159
"followers")) # Tokens valid after
2161
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2162
# the "duration" ABNF definition in RFC 3339, Appendix A.
2163
token_end = Token(re.compile(r"$"), None, frozenset())
2164
token_second = Token(re.compile(r"(\d+)S"),
2165
datetime.timedelta(seconds=1),
2166
frozenset((token_end,)))
2167
token_minute = Token(re.compile(r"(\d+)M"),
2168
datetime.timedelta(minutes=1),
2169
frozenset((token_second, token_end)))
2170
token_hour = Token(re.compile(r"(\d+)H"),
2171
datetime.timedelta(hours=1),
2172
frozenset((token_minute, token_end)))
2173
token_time = Token(re.compile(r"T"),
2175
frozenset((token_hour, token_minute,
2177
token_day = Token(re.compile(r"(\d+)D"),
2178
datetime.timedelta(days=1),
2179
frozenset((token_time, token_end)))
2180
token_month = Token(re.compile(r"(\d+)M"),
2181
datetime.timedelta(weeks=4),
2182
frozenset((token_day, token_end)))
2183
token_year = Token(re.compile(r"(\d+)Y"),
2184
datetime.timedelta(weeks=52),
2185
frozenset((token_month, token_end)))
2186
token_week = Token(re.compile(r"(\d+)W"),
2187
datetime.timedelta(weeks=1),
2188
frozenset((token_end,)))
2189
token_duration = Token(re.compile(r"P"), None,
2190
frozenset((token_year, token_month,
2191
token_day, token_time,
2193
# Define starting values
2194
value = datetime.timedelta() # Value so far
2196
followers = frozenset(token_duration,) # Following valid tokens
2197
s = duration # String left to parse
2198
# Loop until end token is found
2199
while found_token is not token_end:
2200
# Search for any currently valid tokens
2201
for token in followers:
2202
match = token.regexp.match(s)
2203
if match is not None:
2205
if token.value is not None:
2206
# Value found, parse digits
2207
factor = int(match.group(1), 10)
2208
# Add to value so far
2209
value += factor * token.value
2210
# Strip token from string
2211
s = token.regexp.sub("", s, 1)
2214
# Set valid next tokens
2215
followers = found_token.followers
2218
# No currently valid tokens were found
2219
raise ValueError("Invalid RFC 3339 duration")
2224
1801
def string_to_delta(interval):
2225
1802
"""Parse a string and return a datetime.timedelta
2371
1953
# Convert the SafeConfigParser object to a dict
2372
1954
server_settings = server_config.defaults()
2373
1955
# Use the appropriate methods on the non-string config options
2374
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
1956
for option in ("debug", "use_dbus", "use_ipv6"):
2375
1957
server_settings[option] = server_config.getboolean("DEFAULT",
2377
1959
if server_settings["port"]:
2378
1960
server_settings["port"] = server_config.getint("DEFAULT",
2380
if server_settings["socket"]:
2381
server_settings["socket"] = server_config.getint("DEFAULT",
2383
# Later, stdin will, and stdout and stderr might, be dup'ed
2384
# over with an opened os.devnull. But we don't want this to
2385
# happen with a supplied network socket.
2386
if 0 <= server_settings["socket"] <= 2:
2387
server_settings["socket"] = os.dup(server_settings
2389
1962
del server_config
2391
1964
# Override the settings from the config file with command line
2392
1965
# options, if set.
2393
1966
for option in ("interface", "address", "port", "debug",
2394
1967
"priority", "servicename", "configdir",
2395
"use_dbus", "use_ipv6", "debuglevel", "restore",
2396
"statedir", "socket", "foreground"):
1968
"use_dbus", "use_ipv6", "debuglevel", "restore"):
2397
1969
value = getattr(options, option)
2398
1970
if value is not None:
2399
1971
server_settings[option] = value
2548
2111
client_class = Client
2550
client_class = functools.partial(ClientDBus, bus = bus)
2552
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())
2553
2133
old_client_settings = {}
2556
# This is used to redirect stdout and stderr for checker processes
2558
wnull = open(os.devnull, "w") # A writable /dev/null
2559
# Only used if server is running in foreground but not in debug
2561
if debug or not foreground:
2564
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2565
2137
if server_settings["restore"]:
2567
2139
with open(stored_state_path, "rb") as stored_state:
2568
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2570
2141
os.remove(stored_state_path)
2571
2142
except IOError as e:
2572
if e.errno == errno.ENOENT:
2573
logger.warning("Could not load persistent state: {0}"
2574
.format(os.strerror(e.errno)))
2576
logger.critical("Could not load persistent state:",
2143
logger.warning("Could not load persistant state: {0}".format(e))
2144
if e.errno != errno.ENOENT:
2579
except EOFError as e:
2580
logger.warning("Could not load persistent state: "
2581
"EOFError:", exc_info=e)
2583
with PGPEngine() as pgp:
2584
for client_name, client in clients_data.iteritems():
2585
# Skip removed clients
2586
if client_name not in client_settings:
2589
# Decide which value to use after restoring saved state.
2590
# We have three different values: Old config file,
2591
# new config file, and saved state.
2592
# New config value takes precedence if it differs from old
2593
# config value, otherwise use saved state.
2594
for name, value in client_settings[client_name].items():
2596
# For each value in new config, check if it
2597
# differs from the old config value (Except for
2598
# the "secret" attribute)
2599
if (name != "secret" and
2600
value != old_client_settings[client_name]
2602
client[name] = value
2606
# Clients who has passed its expire date can still be
2607
# enabled if its last checker was successful. Clients
2608
# whose checker succeeded before we stored its state is
2609
# assumed to have successfully run all checkers during
2611
if client["enabled"]:
2612
if datetime.datetime.utcnow() >= client["expires"]:
2613
if not client["last_checked_ok"]:
2615
"disabling client {0} - Client never "
2616
"performed a successful checker"
2617
.format(client_name))
2618
client["enabled"] = False
2619
elif client["last_checker_status"] != 0:
2621
"disabling client {0} - Client "
2622
"last checker failed with error code {1}"
2623
.format(client_name,
2624
client["last_checker_status"]))
2625
client["enabled"] = False
2627
client["expires"] = (datetime.datetime
2629
+ client["timeout"])
2630
logger.debug("Last checker succeeded,"
2631
" keeping {0} enabled"
2632
.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():
2634
client["secret"] = (
2635
pgp.decrypt(client["encrypted_secret"],
2636
client_settings[client_name]
2639
# If decryption fails, we use secret from new settings
2640
logger.debug("Failed to decrypt {0} old secret"
2641
.format(client_name))
2642
client["secret"] = (
2643
client_settings[client_name]["secret"])
2645
# Add/remove clients based on new changes made to config
2646
for client_name in (set(old_client_settings)
2647
- set(client_settings)):
2648
del clients_data[client_name]
2649
for client_name in (set(client_settings)
2650
- set(old_client_settings)):
2651
clients_data[client_name] = client_settings[client_name]
2653
# Create all client objects
2654
for client_name, client in clients_data.iteritems():
2655
tcp_server.clients[client_name] = client_class(
2656
name = client_name, settings = client,
2657
server_settings = server_settings)
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,
2659
2211
if not tcp_server.clients:
2660
2212
logger.warning("No clients defined")
2663
if pidfile is not None:
2667
pidfile.write(str(pid) + "\n".encode("utf-8"))
2669
logger.error("Could not write to file %r with PID %d",
2218
pidfile.write(str(pid) + "\n".encode("utf-8"))
2221
logger.error("Could not write to file %r with PID %d",
2224
# "pidfile" was never created
2672
2226
del pidfilename
2228
signal.signal(signal.SIGINT, signal.SIG_IGN)
2674
2230
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2675
2231
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2678
@alternate_dbus_interfaces({"se.recompile.Mandos":
2679
"se.bsnet.fukt.Mandos"})
2680
class MandosDBusService(DBusObjectWithProperties):
2234
class MandosDBusService(dbus.service.Object):
2681
2235
"""A D-Bus proxy object"""
2682
2236
def __init__(self):
2683
2237
dbus.service.Object.__init__(self, bus, "/")
2684
2238
_interface = "se.recompile.Mandos"
2686
@dbus_interface_annotations(_interface)
2688
return { "org.freedesktop.DBus.Property"
2689
".EmitsChangedSignal":
2692
2240
@dbus.service.signal(_interface, signature="o")
2693
2241
def ClientAdded(self, objpath):
2739
mandos_dbus_service = MandosDBusService()
2287
class MandosDBusServiceTransitional(MandosDBusService):
2288
__metaclass__ = AlternateDBusNamesMetaclass
2289
mandos_dbus_service = MandosDBusServiceTransitional()
2742
2292
"Cleanup function; run on exit"
2743
2293
service.cleanup()
2745
2295
multiprocessing.active_children()
2747
2296
if not (tcp_server.clients or client_settings):
2750
# Store client before exiting. Secrets are encrypted with key
2751
# based on what config file has. If config file is
2752
# removed/edited, old secret will thus be unrecovable.
2754
with PGPEngine() as pgp:
2755
for client in tcp_server.clients.itervalues():
2756
key = client_settings[client.name]["secret"]
2757
client.encrypted_secret = pgp.encrypt(client.secret,
2761
# A list of attributes that can not be pickled
2763
exclude = set(("bus", "changedstate", "secret",
2764
"checker", "server_settings"))
2765
for name, typ in (inspect.getmembers
2766
(dbus.service.Object)):
2769
client_dict["encrypted_secret"] = (client
2771
for attr in client.client_structure:
2772
if attr not in exclude:
2773
client_dict[attr] = getattr(client, attr)
2775
clients[client.name] = client_dict
2776
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"]
2779
with (tempfile.NamedTemporaryFile
2780
(mode='wb', suffix=".pickle", prefix='clients-',
2781
dir=os.path.dirname(stored_state_path),
2782
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:
2783
2323
pickle.dump((clients, client_settings), stored_state)
2784
tempname=stored_state.name
2785
os.rename(tempname, stored_state_path)
2786
except (IOError, OSError) as e:
2792
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2793
logger.warning("Could not save persistent state: {0}"
2794
.format(os.strerror(e.errno)))
2796
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:
2800
2329
# Delete all clients, and settings from config
2801
2330
while tcp_server.clients:
2802
2331
name, client = tcp_server.clients.popitem()