84
89
except ImportError:
85
90
SO_BINDTODEVICE = None
90
stored_state_path = "/var/lib/mandos/clients.pickle"
92
#logger = logging.getLogger('mandos')
93
logger = logging.Logger('mandos')
93
stored_state_file = "clients.pickle"
95
logger = logging.getLogger()
94
96
syslogger = (logging.handlers.SysLogHandler
95
97
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
96
98
address = str("/dev/log")))
97
syslogger.setFormatter(logging.Formatter
98
('Mandos [%(process)d]: %(levelname)s:'
100
logger.addHandler(syslogger)
102
console = logging.StreamHandler()
103
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
106
logger.addHandler(console)
101
if_nametoindex = (ctypes.cdll.LoadLibrary
102
(ctypes.util.find_library("c"))
104
except (OSError, AttributeError):
105
def if_nametoindex(interface):
106
"Get an interface index the hard way, i.e. using fcntl()"
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
108
with contextlib.closing(socket.socket()) as s:
109
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
struct.pack(str("16s16x"),
112
interface_index = struct.unpack(str("I"),
114
return interface_index
117
def initlogger(debug, level=logging.WARNING):
118
"""init logger and add loglevel"""
120
syslogger.setFormatter(logging.Formatter
121
('Mandos [%(process)d]: %(levelname)s:'
123
logger.addHandler(syslogger)
126
console = logging.StreamHandler()
127
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
131
logger.addHandler(console)
132
logger.setLevel(level)
135
class PGPError(Exception):
136
"""Exception if encryption/decryption fails"""
140
class PGPEngine(object):
141
"""A simple class for OpenPGP symmetric encryption & decryption"""
143
self.gnupg = GnuPGInterface.GnuPG()
144
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
145
self.gnupg = GnuPGInterface.GnuPG()
146
self.gnupg.options.meta_interactive = False
147
self.gnupg.options.homedir = self.tempdir
148
self.gnupg.options.extra_args.extend(['--force-mdc',
155
def __exit__(self, exc_type, exc_value, traceback):
163
if self.tempdir is not None:
164
# Delete contents of tempdir
165
for root, dirs, files in os.walk(self.tempdir,
167
for filename in files:
168
os.remove(os.path.join(root, filename))
170
os.rmdir(os.path.join(root, dirname))
172
os.rmdir(self.tempdir)
175
def password_encode(self, password):
176
# Passphrase can not be empty and can not contain newlines or
177
# NUL bytes. So we prefix it and hex encode it.
178
return b"mandos" + binascii.hexlify(password)
180
def encrypt(self, data, password):
181
self.gnupg.passphrase = self.password_encode(password)
182
with open(os.devnull, "w") as devnull:
184
proc = self.gnupg.run(['--symmetric'],
185
create_fhs=['stdin', 'stdout'],
186
attach_fhs={'stderr': devnull})
187
with contextlib.closing(proc.handles['stdin']) as f:
189
with contextlib.closing(proc.handles['stdout']) as f:
190
ciphertext = f.read()
194
self.gnupg.passphrase = None
197
def decrypt(self, data, password):
198
self.gnupg.passphrase = self.password_encode(password)
199
with open(os.devnull, "w") as devnull:
201
proc = self.gnupg.run(['--decrypt'],
202
create_fhs=['stdin', 'stdout'],
203
attach_fhs={'stderr': devnull})
204
with contextlib.closing(proc.handles['stdin']) as f:
206
with contextlib.closing(proc.handles['stdout']) as f:
207
decrypted_plaintext = f.read()
211
self.gnupg.passphrase = None
212
return decrypted_plaintext
108
215
class AvahiError(Exception):
109
216
def __init__(self, value, *args, **kwargs):
304
427
interval: datetime.timedelta(); How often to start a new checker
305
428
last_approval_request: datetime.datetime(); (UTC) or None
306
429
last_checked_ok: datetime.datetime(); (UTC) or None
307
Last_checker_status: integer between 0 and 255 reflecting exit status
308
of last checker. -1 reflect crashed checker.
309
last_enabled: datetime.datetime(); (UTC)
430
last_checker_status: integer between 0 and 255 reflecting exit
431
status of last checker. -1 reflects crashed
432
checker, -2 means no checker completed yet.
433
last_enabled: datetime.datetime(); (UTC) or None
310
434
name: string; from the config file, used in log messages and
311
435
D-Bus identifiers
312
436
secret: bytestring; sent verbatim (over TLS) to client
313
437
timeout: datetime.timedelta(); How long from last_checked_ok
314
438
until this client is disabled
315
extended_timeout: extra long timeout when password has been sent
439
extended_timeout: extra long timeout when secret has been sent
316
440
runtime_expansions: Allowed attributes for runtime expansion.
317
441
expires: datetime.datetime(); time (UTC) when a client will be
318
442
disabled, or None
321
445
runtime_expansions = ("approval_delay", "approval_duration",
322
"created", "enabled", "fingerprint",
323
"host", "interval", "last_checked_ok",
446
"created", "enabled", "expires",
447
"fingerprint", "host", "interval",
448
"last_approval_request", "last_checked_ok",
324
449
"last_enabled", "name", "timeout")
450
client_defaults = { "timeout": "PT5M",
451
"extended_timeout": "PT15M",
453
"checker": "fping -q -- %%(host)s",
455
"approval_delay": "PT0S",
456
"approval_duration": "PT1S",
457
"approved_by_default": "True",
326
461
def timeout_milliseconds(self):
327
462
"Return the 'timeout' attribute in milliseconds"
328
return _timedelta_to_milliseconds(self.timeout)
463
return timedelta_to_milliseconds(self.timeout)
330
465
def extended_timeout_milliseconds(self):
331
466
"Return the 'extended_timeout' attribute in milliseconds"
332
return _timedelta_to_milliseconds(self.extended_timeout)
467
return timedelta_to_milliseconds(self.extended_timeout)
334
469
def interval_milliseconds(self):
335
470
"Return the 'interval' attribute in milliseconds"
336
return _timedelta_to_milliseconds(self.interval)
471
return timedelta_to_milliseconds(self.interval)
338
473
def approval_delay_milliseconds(self):
339
return _timedelta_to_milliseconds(self.approval_delay)
341
def __init__(self, name = None, config=None):
342
"""Note: the 'checker' key in 'config' sets the
343
'checker_command' attribute and *not* the 'checker'
474
return timedelta_to_milliseconds(self.approval_delay)
477
def config_parser(config):
478
"""Construct a new dict of client settings of this form:
479
{ client_name: {setting_name: value, ...}, ...}
480
with exceptions for any special settings as defined above.
481
NOTE: Must be a pure function. Must return the same result
482
value given the same arguments.
485
for client_name in config.sections():
486
section = dict(config.items(client_name))
487
client = settings[client_name] = {}
489
client["host"] = section["host"]
490
# Reformat values from string types to Python types
491
client["approved_by_default"] = config.getboolean(
492
client_name, "approved_by_default")
493
client["enabled"] = config.getboolean(client_name,
496
client["fingerprint"] = (section["fingerprint"].upper()
498
if "secret" in section:
499
client["secret"] = section["secret"].decode("base64")
500
elif "secfile" in section:
501
with open(os.path.expanduser(os.path.expandvars
502
(section["secfile"])),
504
client["secret"] = secfile.read()
506
raise TypeError("No secret or secfile for section {0}"
508
client["timeout"] = string_to_delta(section["timeout"])
509
client["extended_timeout"] = string_to_delta(
510
section["extended_timeout"])
511
client["interval"] = string_to_delta(section["interval"])
512
client["approval_delay"] = string_to_delta(
513
section["approval_delay"])
514
client["approval_duration"] = string_to_delta(
515
section["approval_duration"])
516
client["checker_command"] = section["checker"]
517
client["last_approval_request"] = None
518
client["last_checked_ok"] = None
519
client["last_checker_status"] = -2
523
def __init__(self, settings, name = None):
525
# adding all client settings
526
for setting, value in settings.iteritems():
527
setattr(self, setting, value)
530
if not hasattr(self, "last_enabled"):
531
self.last_enabled = datetime.datetime.utcnow()
532
if not hasattr(self, "expires"):
533
self.expires = (datetime.datetime.utcnow()
536
self.last_enabled = None
348
539
logger.debug("Creating client %r", self.name)
349
540
# Uppercase and remove spaces from fingerprint for later
350
541
# comparison purposes with return value from the fingerprint()
352
self.fingerprint = (config["fingerprint"].upper()
354
543
logger.debug(" Fingerprint: %s", self.fingerprint)
355
if "secret" in config:
356
self.secret = config["secret"].decode("base64")
357
elif "secfile" in config:
358
with open(os.path.expanduser(os.path.expandvars
359
(config["secfile"])),
361
self.secret = secfile.read()
363
raise TypeError("No secret or secfile for client %s"
365
self.host = config.get("host", "")
366
self.created = datetime.datetime.utcnow()
368
self.last_approval_request = None
369
self.last_enabled = datetime.datetime.utcnow()
370
self.last_checked_ok = None
371
self.last_checker_status = 0
372
self.timeout = string_to_delta(config["timeout"])
373
self.extended_timeout = string_to_delta(config
374
["extended_timeout"])
375
self.interval = string_to_delta(config["interval"])
544
self.created = settings.get("created",
545
datetime.datetime.utcnow())
547
# attributes specific for this server instance
376
548
self.checker = None
377
549
self.checker_initiator_tag = None
378
550
self.disable_initiator_tag = None
379
self.expires = datetime.datetime.utcnow() + self.timeout
380
551
self.checker_callback_tag = None
381
self.checker_command = config["checker"]
382
552
self.current_checker_command = None
383
self._approved = None
384
self.approved_by_default = config.get("approved_by_default",
386
554
self.approvals_pending = 0
387
self.approval_delay = string_to_delta(
388
config["approval_delay"])
389
self.approval_duration = string_to_delta(
390
config["approval_duration"])
391
555
self.changedstate = (multiprocessing_manager
392
556
.Condition(multiprocessing_manager
394
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
558
self.client_structure = [attr for attr in
559
self.__dict__.iterkeys()
560
if not attr.startswith("_")]
395
561
self.client_structure.append("client_structure")
398
563
for name, t in inspect.getmembers(type(self),
399
lambda obj: isinstance(obj, property)):
400
567
if not name.startswith("_"):
401
568
self.client_structure.append(name)
570
# Send notice to process children that client state has changed
404
571
def send_changedstate(self):
405
self.changedstate.acquire()
406
self.changedstate.notify_all()
407
self.changedstate.release()
572
with self.changedstate:
573
self.changedstate.notify_all()
409
575
def enable(self):
410
576
"""Start this client's checker and timeout hooks"""
411
577
if getattr(self, "enabled", False):
412
578
# Already enabled
414
self.send_changedstate()
415
580
self.expires = datetime.datetime.utcnow() + self.timeout
416
581
self.enabled = True
417
582
self.last_enabled = datetime.datetime.utcnow()
418
583
self.init_checker()
584
self.send_changedstate()
420
586
def disable(self, quiet=True):
421
587
"""Disable this client."""
422
588
if not getattr(self, "enabled", False):
425
self.send_changedstate()
427
591
logger.info("Disabling client %s", self.name)
428
if getattr(self, "disable_initiator_tag", False):
592
if getattr(self, "disable_initiator_tag", None) is not None:
429
593
gobject.source_remove(self.disable_initiator_tag)
430
594
self.disable_initiator_tag = None
431
595
self.expires = None
432
if getattr(self, "checker_initiator_tag", False):
596
if getattr(self, "checker_initiator_tag", None) is not None:
433
597
gobject.source_remove(self.checker_initiator_tag)
434
598
self.checker_initiator_tag = None
435
599
self.stop_checker()
436
600
self.enabled = False
602
self.send_changedstate()
437
603
# Do not run this again if called by a gobject.timeout_add
440
606
def __del__(self):
443
609
def init_checker(self):
444
610
# Schedule a new checker to be started an 'interval' from now,
445
611
# and every interval from then on.
612
if self.checker_initiator_tag is not None:
613
gobject.source_remove(self.checker_initiator_tag)
446
614
self.checker_initiator_tag = (gobject.timeout_add
447
615
(self.interval_milliseconds(),
448
616
self.start_checker))
449
617
# Schedule a disable() when 'timeout' has passed
618
if self.disable_initiator_tag is not None:
619
gobject.source_remove(self.disable_initiator_tag)
450
620
self.disable_initiator_tag = (gobject.timeout_add
451
621
(self.timeout_milliseconds(),
453
623
# Also start a new checker *right now*.
454
624
self.start_checker()
457
626
def checker_callback(self, pid, condition, command):
458
627
"""The checker has completed, so take appropriate actions."""
459
628
self.checker_callback_tag = None
460
629
self.checker = None
461
630
if os.WIFEXITED(condition):
462
self.last_checker_status = os.WEXITSTATUS(condition)
631
self.last_checker_status = os.WEXITSTATUS(condition)
463
632
if self.last_checker_status == 0:
464
633
logger.info("Checker for %(name)s succeeded",
577
740
logger.debug("Stopping checker for %(name)s", vars(self))
579
os.kill(self.checker.pid, signal.SIGTERM)
742
self.checker.terminate()
581
744
#if self.checker.poll() is None:
582
# os.kill(self.checker.pid, signal.SIGKILL)
745
# self.checker.kill()
583
746
except OSError as error:
584
747
if error.errno != errno.ESRCH: # No such process
586
749
self.checker = None
588
# Encrypts a client secret and stores it in a varible encrypted_secret
589
def encrypt_secret(self, key):
590
# Encryption-key need to be specific size, so we hash inputed key
591
hasheng = hashlib.sha256()
593
encryptionkey = hasheng.digest()
595
# Create validation hash so we know at decryption if it was sucessful
596
hasheng = hashlib.sha256()
597
hasheng.update(self.secret)
598
validationhash = hasheng.digest()
601
iv = os.urandom(Crypto.Cipher.AES.block_size)
602
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
603
Crypto.Cipher.AES.MODE_CFB, iv)
604
ciphertext = ciphereng.encrypt(validationhash+self.secret)
605
self.encrypted_secret = (ciphertext, iv)
607
# Decrypt a encrypted client secret
608
def decrypt_secret(self, key):
609
# Decryption-key need to be specific size, so we hash inputed key
610
hasheng = hashlib.sha256()
612
encryptionkey = hasheng.digest()
614
# Decrypt encrypted secret
615
ciphertext, iv = self.encrypted_secret
616
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
617
Crypto.Cipher.AES.MODE_CFB, iv)
618
plain = ciphereng.decrypt(ciphertext)
620
# Validate decrypted secret to know if it was succesful
621
hasheng = hashlib.sha256()
622
validationhash = plain[:hasheng.digest_size]
623
secret = plain[hasheng.digest_size:]
624
hasheng.update(secret)
626
# if validation fails, we use key as new secret. Otherwhise, we use
627
# the decrypted secret
628
if hasheng.digest() == validationhash:
632
del self.encrypted_secret
635
752
def dbus_service_property(dbus_interface, signature="v",
636
753
access="readwrite", byte_arrays=False):
815
1013
except (AttributeError, xml.dom.DOMException,
816
1014
xml.parsers.expat.ExpatError) as error:
817
1015
logger.error("Failed to override Introspection method",
819
1017
return xmlstring
822
def datetime_to_dbus (dt, variant_level=0):
1020
def datetime_to_dbus(dt, variant_level=0):
823
1021
"""Convert a UTC datetime.datetime() to a D-Bus type."""
825
1023
return dbus.String("", variant_level = variant_level)
826
1024
return dbus.String(dt.isoformat(),
827
1025
variant_level=variant_level)
829
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
831
"""Applied to an empty subclass of a D-Bus object, this metaclass
832
will add additional D-Bus attributes matching a certain pattern.
1028
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1029
"""A class decorator; applied to a subclass of
1030
dbus.service.Object, it will add alternate D-Bus attributes with
1031
interface names according to the "alt_interface_names" mapping.
1034
@alternate_dbus_interfaces({"org.example.Interface":
1035
"net.example.AlternateInterface"})
1036
class SampleDBusObject(dbus.service.Object):
1037
@dbus.service.method("org.example.Interface")
1038
def SampleDBusMethod():
1041
The above "SampleDBusMethod" on "SampleDBusObject" will be
1042
reachable via two interfaces: "org.example.Interface" and
1043
"net.example.AlternateInterface", the latter of which will have
1044
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1045
"true", unless "deprecate" is passed with a False value.
1047
This works for methods and signals, and also for D-Bus properties
1048
(from DBusObjectWithProperties) and interfaces (from the
1049
dbus_interface_annotations decorator).
834
def __new__(mcs, name, bases, attr):
835
# Go through all the base classes which could have D-Bus
836
# methods, signals, or properties in them
837
for base in (b for b in bases
838
if issubclass(b, dbus.service.Object)):
839
# Go though all attributes of the base class
840
for attrname, attribute in inspect.getmembers(base):
1052
for orig_interface_name, alt_interface_name in (
1053
alt_interface_names.iteritems()):
1055
interface_names = set()
1056
# Go though all attributes of the class
1057
for attrname, attribute in inspect.getmembers(cls):
841
1058
# Ignore non-D-Bus attributes, and D-Bus attributes
842
1059
# with the wrong interface name
843
1060
if (not hasattr(attribute, "_dbus_interface")
844
1061
or not attribute._dbus_interface
845
.startswith("se.recompile.Mandos")):
1062
.startswith(orig_interface_name)):
847
1064
# Create an alternate D-Bus interface name based on
848
1065
# the current name
849
1066
alt_interface = (attribute._dbus_interface
850
.replace("se.recompile.Mandos",
851
"se.bsnet.fukt.Mandos"))
1067
.replace(orig_interface_name,
1068
alt_interface_name))
1069
interface_names.add(alt_interface)
852
1070
# Is this a D-Bus signal?
853
1071
if getattr(attribute, "_dbus_is_signal", False):
854
1072
# Extract the original non-method function by
992
1262
checker is not None)
993
1263
last_checked_ok = notifychangeproperty(datetime_to_dbus,
994
1264
"LastCheckedOK")
1265
last_checker_status = notifychangeproperty(dbus.Int16,
1266
"LastCheckerStatus")
995
1267
last_approval_request = notifychangeproperty(
996
1268
datetime_to_dbus, "LastApprovalRequest")
997
1269
approved_by_default = notifychangeproperty(dbus.Boolean,
998
1270
"ApprovedByDefault")
999
approval_delay = notifychangeproperty(dbus.UInt16,
1271
approval_delay = notifychangeproperty(dbus.UInt64,
1000
1272
"ApprovalDelay",
1002
_timedelta_to_milliseconds)
1274
timedelta_to_milliseconds)
1003
1275
approval_duration = notifychangeproperty(
1004
dbus.UInt16, "ApprovalDuration",
1005
type_func = _timedelta_to_milliseconds)
1276
dbus.UInt64, "ApprovalDuration",
1277
type_func = timedelta_to_milliseconds)
1006
1278
host = notifychangeproperty(dbus.String, "Host")
1007
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1279
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1009
_timedelta_to_milliseconds)
1281
timedelta_to_milliseconds)
1010
1282
extended_timeout = notifychangeproperty(
1011
dbus.UInt16, "ExtendedTimeout",
1012
type_func = _timedelta_to_milliseconds)
1013
interval = notifychangeproperty(dbus.UInt16,
1283
dbus.UInt64, "ExtendedTimeout",
1284
type_func = timedelta_to_milliseconds)
1285
interval = notifychangeproperty(dbus.UInt64,
1016
_timedelta_to_milliseconds)
1288
timedelta_to_milliseconds)
1017
1289
checker_command = notifychangeproperty(dbus.String, "Checker")
1019
1291
del notifychangeproperty
1619
1900
use_ipv6: Boolean; to use IPv6 or not
1621
1902
def __init__(self, server_address, RequestHandlerClass,
1622
interface=None, use_ipv6=True):
1903
interface=None, use_ipv6=True, socketfd=None):
1904
"""If socketfd is set, use that file descriptor instead of
1905
creating a new one with socket.socket().
1623
1907
self.interface = interface
1625
1909
self.address_family = socket.AF_INET6
1910
if socketfd is not None:
1911
# Save the file descriptor
1912
self.socketfd = socketfd
1913
# Save the original socket.socket() function
1914
self.socket_socket = socket.socket
1915
# To implement --socket, we monkey patch socket.socket.
1917
# (When socketserver.TCPServer is a new-style class, we
1918
# could make self.socket into a property instead of monkey
1919
# patching socket.socket.)
1921
# Create a one-time-only replacement for socket.socket()
1922
@functools.wraps(socket.socket)
1923
def socket_wrapper(*args, **kwargs):
1924
# Restore original function so subsequent calls are
1926
socket.socket = self.socket_socket
1927
del self.socket_socket
1928
# This time only, return a new socket object from the
1929
# saved file descriptor.
1930
return socket.fromfd(self.socketfd, *args, **kwargs)
1931
# Replace socket.socket() function with wrapper
1932
socket.socket = socket_wrapper
1933
# The socketserver.TCPServer.__init__ will call
1934
# socket.socket(), which might be our replacement,
1935
# socket_wrapper(), if socketfd was set.
1626
1936
socketserver.TCPServer.__init__(self, server_address,
1627
1937
RequestHandlerClass)
1628
1939
def server_bind(self):
1629
1940
"""This overrides the normal server_bind() function
1630
1941
to bind to an interface if one was specified, and also NOT to
2094
def rfc3339_duration_to_delta(duration):
2095
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2097
>>> rfc3339_duration_to_delta("P7D")
2098
datetime.timedelta(7)
2099
>>> rfc3339_duration_to_delta("PT60S")
2100
datetime.timedelta(0, 60)
2101
>>> rfc3339_duration_to_delta("PT60M")
2102
datetime.timedelta(0, 3600)
2103
>>> rfc3339_duration_to_delta("PT24H")
2104
datetime.timedelta(1)
2105
>>> rfc3339_duration_to_delta("P1W")
2106
datetime.timedelta(7)
2107
>>> rfc3339_duration_to_delta("PT5M30S")
2108
datetime.timedelta(0, 330)
2109
>>> rfc3339_duration_to_delta("P1DT3M20S")
2110
datetime.timedelta(1, 200)
2113
# Parsing an RFC 3339 duration with regular expressions is not
2114
# possible - there would have to be multiple places for the same
2115
# values, like seconds. The current code, while more esoteric, is
2116
# cleaner without depending on a parsing library. If Python had a
2117
# built-in library for parsing we would use it, but we'd like to
2118
# avoid excessive use of external libraries.
2120
# New type for defining tokens, syntax, and semantics all-in-one
2121
Token = collections.namedtuple("Token",
2122
("regexp", # To match token; if
2123
# "value" is not None,
2124
# must have a "group"
2126
"value", # datetime.timedelta or
2128
"followers")) # Tokens valid after
2130
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2131
# the "duration" ABNF definition in RFC 3339, Appendix A.
2132
token_end = Token(re.compile(r"$"), None, frozenset())
2133
token_second = Token(re.compile(r"(\d+)S"),
2134
datetime.timedelta(seconds=1),
2135
frozenset((token_end,)))
2136
token_minute = Token(re.compile(r"(\d+)M"),
2137
datetime.timedelta(minutes=1),
2138
frozenset((token_second, token_end)))
2139
token_hour = Token(re.compile(r"(\d+)H"),
2140
datetime.timedelta(hours=1),
2141
frozenset((token_minute, token_end)))
2142
token_time = Token(re.compile(r"T"),
2144
frozenset((token_hour, token_minute,
2146
token_day = Token(re.compile(r"(\d+)D"),
2147
datetime.timedelta(days=1),
2148
frozenset((token_time, token_end)))
2149
token_month = Token(re.compile(r"(\d+)M"),
2150
datetime.timedelta(weeks=4),
2151
frozenset((token_day, token_end)))
2152
token_year = Token(re.compile(r"(\d+)Y"),
2153
datetime.timedelta(weeks=52),
2154
frozenset((token_month, token_end)))
2155
token_week = Token(re.compile(r"(\d+)W"),
2156
datetime.timedelta(weeks=1),
2157
frozenset((token_end,)))
2158
token_duration = Token(re.compile(r"P"), None,
2159
frozenset((token_year, token_month,
2160
token_day, token_time,
2162
# Define starting values
2163
value = datetime.timedelta() # Value so far
2165
followers = frozenset(token_duration,) # Following valid tokens
2166
s = duration # String left to parse
2167
# Loop until end token is found
2168
while found_token is not token_end:
2169
# Search for any currently valid tokens
2170
for token in followers:
2171
match = token.regexp.match(s)
2172
if match is not None:
2174
if token.value is not None:
2175
# Value found, parse digits
2176
factor = int(match.group(1), 10)
2177
# Add to value so far
2178
value += factor * token.value
2179
# Strip token from string
2180
s = token.regexp.sub("", s, 1)
2183
# Set valid next tokens
2184
followers = found_token.followers
2187
# No currently valid tokens were found
2188
raise ValueError("Invalid RFC 3339 duration")
1795
2193
def string_to_delta(interval):
1796
2194
"""Parse a string and return a datetime.timedelta
2105
2510
client_class = Client
2107
client_class = functools.partial(ClientDBusTransitional,
2110
special_settings = {
2111
# Some settings need to be accessd by special methods;
2112
# booleans need .getboolean(), etc. Here is a list of them:
2113
"approved_by_default":
2115
client_config.getboolean(section, "approved_by_default"),
2117
# Construct a new dict of client settings of this form:
2118
# { client_name: {setting_name: value, ...}, ...}
2119
# with exceptions for any special settings as defined above
2120
client_settings = dict((clientname,
2122
(value if setting not in special_settings
2123
else special_settings[setting](clientname)))
2124
for setting, value in client_config.items(clientname)))
2125
for clientname in client_config.sections())
2512
client_class = functools.partial(ClientDBus, bus = bus)
2514
client_settings = Client.config_parser(client_config)
2127
2515
old_client_settings = {}
2518
# Get client data and settings from last running state.
2130
2519
if server_settings["restore"]:
2132
2521
with open(stored_state_path, "rb") as stored_state:
2133
clients_data, old_client_settings = pickle.load(stored_state)
2522
clients_data, old_client_settings = (pickle.load
2134
2524
os.remove(stored_state_path)
2135
2525
except IOError as e:
2136
logger.warning("Could not load persistant state: {0}".format(e))
2137
if e.errno != errno.ENOENT:
2526
if e.errno == errno.ENOENT:
2527
logger.warning("Could not load persistent state: {0}"
2528
.format(os.strerror(e.errno)))
2530
logger.critical("Could not load persistent state:",
2140
for client in clients_data:
2141
client_name = client["name"]
2143
# Decide which value to use after restoring saved state.
2144
# We have three different values: Old config file,
2145
# new config file, and saved state.
2146
# New config value takes precedence if it differs from old
2147
# config value, otherwise use saved state.
2148
for name, value in client_settings[client_name].items():
2533
except EOFError as e:
2534
logger.warning("Could not load persistent state: "
2535
"EOFError:", exc_info=e)
2537
with PGPEngine() as pgp:
2538
for client_name, client in clients_data.iteritems():
2539
# Decide which value to use after restoring saved state.
2540
# We have three different values: Old config file,
2541
# new config file, and saved state.
2542
# New config value takes precedence if it differs from old
2543
# config value, otherwise use saved state.
2544
for name, value in client_settings[client_name].items():
2546
# For each value in new config, check if it
2547
# differs from the old config value (Except for
2548
# the "secret" attribute)
2549
if (name != "secret" and
2550
value != old_client_settings[client_name]
2552
client[name] = value
2556
# Clients who has passed its expire date can still be
2557
# enabled if its last checker was successful. Clients
2558
# whose checker succeeded before we stored its state is
2559
# assumed to have successfully run all checkers during
2561
if client["enabled"]:
2562
if datetime.datetime.utcnow() >= client["expires"]:
2563
if not client["last_checked_ok"]:
2565
"disabling client {0} - Client never "
2566
"performed a successful checker"
2567
.format(client_name))
2568
client["enabled"] = False
2569
elif client["last_checker_status"] != 0:
2571
"disabling client {0} - Client "
2572
"last checker failed with error code {1}"
2573
.format(client_name,
2574
client["last_checker_status"]))
2575
client["enabled"] = False
2577
client["expires"] = (datetime.datetime
2579
+ client["timeout"])
2580
logger.debug("Last checker succeeded,"
2581
" keeping {0} enabled"
2582
.format(client_name))
2150
# For each value in new config, check if it differs
2151
# from the old config value (Except for the "secret"
2153
if name != "secret" and value != old_client_settings[client_name][name]:
2154
setattr(client, name, value)
2158
# Clients who has passed its expire date, can still be enabled if its
2159
# last checker was sucessful. Clients who checkers failed before we
2160
# stored it state is asumed to had failed checker during downtime.
2161
if client["enabled"] and client["last_checked_ok"]:
2162
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2163
> client["interval"]):
2164
if client["last_checker_status"] != 0:
2165
client["enabled"] = False
2167
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2169
client["changedstate"] = (multiprocessing_manager
2170
.Condition(multiprocessing_manager
2173
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2174
tcp_server.clients[client_name] = new_client
2175
new_client.bus = bus
2176
for name, value in client.iteritems():
2177
setattr(new_client, name, value)
2178
client_object_name = unicode(client_name).translate(
2179
{ord("."): ord("_"),
2180
ord("-"): ord("_")})
2181
new_client.dbus_object_path = (dbus.ObjectPath
2182
("/clients/" + client_object_name))
2183
DBusObjectWithProperties.__init__(new_client,
2185
new_client.dbus_object_path)
2187
tcp_server.clients[client_name] = Client.__new__(Client)
2188
for name, value in client.iteritems():
2189
setattr(tcp_server.clients[client_name], name, value)
2191
tcp_server.clients[client_name].decrypt_secret(
2192
client_settings[client_name]["secret"])
2194
# Create/remove clients based on new changes made to config
2195
for clientname in set(old_client_settings) - set(client_settings):
2196
del tcp_server.clients[clientname]
2197
for clientname in set(client_settings) - set(old_client_settings):
2198
tcp_server.clients[clientname] = (client_class(name = clientname,
2584
client["secret"] = (
2585
pgp.decrypt(client["encrypted_secret"],
2586
client_settings[client_name]
2589
# If decryption fails, we use secret from new settings
2590
logger.debug("Failed to decrypt {0} old secret"
2591
.format(client_name))
2592
client["secret"] = (
2593
client_settings[client_name]["secret"])
2595
# Add/remove clients based on new changes made to config
2596
for client_name in (set(old_client_settings)
2597
- set(client_settings)):
2598
del clients_data[client_name]
2599
for client_name in (set(client_settings)
2600
- set(old_client_settings)):
2601
clients_data[client_name] = client_settings[client_name]
2603
# Create all client objects
2604
for client_name, client in clients_data.iteritems():
2605
tcp_server.clients[client_name] = client_class(
2606
name = client_name, settings = client)
2204
2608
if not tcp_server.clients:
2205
2609
logger.warning("No clients defined")
2211
pidfile.write(str(pid) + "\n".encode("utf-8"))
2214
logger.error("Could not write to file %r with PID %d",
2217
# "pidfile" was never created
2612
if pidfile is not None:
2616
pidfile.write(str(pid) + "\n".encode("utf-8"))
2618
logger.error("Could not write to file %r with PID %d",
2219
2621
del pidfilename
2221
signal.signal(signal.SIGINT, signal.SIG_IGN)
2223
2623
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2224
2624
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2227
class MandosDBusService(dbus.service.Object):
2627
@alternate_dbus_interfaces({"se.recompile.Mandos":
2628
"se.bsnet.fukt.Mandos"})
2629
class MandosDBusService(DBusObjectWithProperties):
2228
2630
"""A D-Bus proxy object"""
2229
2631
def __init__(self):
2230
2632
dbus.service.Object.__init__(self, bus, "/")
2231
2633
_interface = "se.recompile.Mandos"
2635
@dbus_interface_annotations(_interface)
2637
return { "org.freedesktop.DBus.Property"
2638
".EmitsChangedSignal":
2233
2641
@dbus.service.signal(_interface, signature="o")
2234
2642
def ClientAdded(self, objpath):
2288
2694
multiprocessing.active_children()
2289
2695
if not (tcp_server.clients or client_settings):
2292
# Store client before exiting. Secrets are encrypted with key based
2293
# on what config file has. If config file is removed/edited, old
2294
# secret will thus be unrecovable.
2296
for client in tcp_server.clients.itervalues():
2297
client.encrypt_secret(client_settings[client.name]["secret"])
2301
# A list of attributes that will not be stored when shuting down.
2302
exclude = set(("bus", "changedstate", "secret"))
2303
for name, typ in inspect.getmembers(dbus.service.Object):
2306
client_dict["encrypted_secret"] = client.encrypted_secret
2307
for attr in client.client_structure:
2308
if attr not in exclude:
2309
client_dict[attr] = getattr(client, attr)
2311
clients.append(client_dict)
2312
del client_settings[client.name]["secret"]
2698
# Store client before exiting. Secrets are encrypted with key
2699
# based on what config file has. If config file is
2700
# removed/edited, old secret will thus be unrecovable.
2702
with PGPEngine() as pgp:
2703
for client in tcp_server.clients.itervalues():
2704
key = client_settings[client.name]["secret"]
2705
client.encrypted_secret = pgp.encrypt(client.secret,
2709
# A list of attributes that can not be pickled
2711
exclude = set(("bus", "changedstate", "secret",
2713
for name, typ in (inspect.getmembers
2714
(dbus.service.Object)):
2717
client_dict["encrypted_secret"] = (client
2719
for attr in client.client_structure:
2720
if attr not in exclude:
2721
client_dict[attr] = getattr(client, attr)
2723
clients[client.name] = client_dict
2724
del client_settings[client.name]["secret"]
2315
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2727
with (tempfile.NamedTemporaryFile
2728
(mode='wb', suffix=".pickle", prefix='clients-',
2729
dir=os.path.dirname(stored_state_path),
2730
delete=False)) as stored_state:
2316
2731
pickle.dump((clients, client_settings), stored_state)
2317
except IOError as e:
2318
logger.warning("Could not save persistant state: {0}".format(e))
2319
if e.errno != errno.ENOENT:
2732
tempname=stored_state.name
2733
os.rename(tempname, stored_state_path)
2734
except (IOError, OSError) as e:
2740
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2741
logger.warning("Could not save persistent state: {0}"
2742
.format(os.strerror(e.errno)))
2744
logger.warning("Could not save persistent state:",
2322
2748
# Delete all clients, and settings from config
2323
2749
while tcp_server.clients:
2324
2750
name, client = tcp_server.clients.popitem()