119
122
logger.addHandler(syslogger)
121
console = logging.StreamHandler()
122
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
126
logger.addHandler(console)
125
console = logging.StreamHandler()
126
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
130
logger.addHandler(console)
127
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
130
214
class AvahiError(Exception):
131
215
def __init__(self, value, *args, **kwargs):
132
216
self.value = value
331
426
interval: datetime.timedelta(); How often to start a new checker
332
427
last_approval_request: datetime.datetime(); (UTC) or None
333
428
last_checked_ok: datetime.datetime(); (UTC) or None
334
last_checker_status: integer between 0 and 255 reflecting exit status
335
of last checker. -1 reflect crashed checker,
337
last_enabled: datetime.datetime(); (UTC)
429
last_checker_status: integer between 0 and 255 reflecting exit
430
status of last checker. -1 reflects crashed
431
checker, -2 means no checker completed yet.
432
last_enabled: datetime.datetime(); (UTC) or None
338
433
name: string; from the config file, used in log messages and
339
434
D-Bus identifiers
340
435
secret: bytestring; sent verbatim (over TLS) to client
341
436
timeout: datetime.timedelta(); How long from last_checked_ok
342
437
until this client is disabled
343
extended_timeout: extra long timeout when password has been sent
438
extended_timeout: extra long timeout when secret has been sent
344
439
runtime_expansions: Allowed attributes for runtime expansion.
345
440
expires: datetime.datetime(); time (UTC) when a client will be
346
441
disabled, or None
349
444
runtime_expansions = ("approval_delay", "approval_duration",
350
"created", "enabled", "fingerprint",
351
"host", "interval", "last_checked_ok",
445
"created", "enabled", "expires",
446
"fingerprint", "host", "interval",
447
"last_approval_request", "last_checked_ok",
352
448
"last_enabled", "name", "timeout")
449
client_defaults = { "timeout": "5m",
450
"extended_timeout": "15m",
452
"checker": "fping -q -- %%(host)s",
454
"approval_delay": "0s",
455
"approval_duration": "1s",
456
"approved_by_default": "True",
354
460
def timeout_milliseconds(self):
355
461
"Return the 'timeout' attribute in milliseconds"
356
return _timedelta_to_milliseconds(self.timeout)
462
return timedelta_to_milliseconds(self.timeout)
358
464
def extended_timeout_milliseconds(self):
359
465
"Return the 'extended_timeout' attribute in milliseconds"
360
return _timedelta_to_milliseconds(self.extended_timeout)
466
return timedelta_to_milliseconds(self.extended_timeout)
362
468
def interval_milliseconds(self):
363
469
"Return the 'interval' attribute in milliseconds"
364
return _timedelta_to_milliseconds(self.interval)
470
return timedelta_to_milliseconds(self.interval)
366
472
def approval_delay_milliseconds(self):
367
return _timedelta_to_milliseconds(self.approval_delay)
369
def __init__(self, name = None, config=None):
370
"""Note: the 'checker' key in 'config' sets the
371
'checker_command' attribute and *not* the 'checker'
473
return timedelta_to_milliseconds(self.approval_delay)
476
def config_parser(config):
477
"""Construct a new dict of client settings of this form:
478
{ client_name: {setting_name: value, ...}, ...}
479
with exceptions for any special settings as defined above.
480
NOTE: Must be a pure function. Must return the same result
481
value given the same arguments.
484
for client_name in config.sections():
485
section = dict(config.items(client_name))
486
client = settings[client_name] = {}
488
client["host"] = section["host"]
489
# Reformat values from string types to Python types
490
client["approved_by_default"] = config.getboolean(
491
client_name, "approved_by_default")
492
client["enabled"] = config.getboolean(client_name,
495
client["fingerprint"] = (section["fingerprint"].upper()
497
if "secret" in section:
498
client["secret"] = section["secret"].decode("base64")
499
elif "secfile" in section:
500
with open(os.path.expanduser(os.path.expandvars
501
(section["secfile"])),
503
client["secret"] = secfile.read()
505
raise TypeError("No secret or secfile for section {0}"
507
client["timeout"] = string_to_delta(section["timeout"])
508
client["extended_timeout"] = string_to_delta(
509
section["extended_timeout"])
510
client["interval"] = string_to_delta(section["interval"])
511
client["approval_delay"] = string_to_delta(
512
section["approval_delay"])
513
client["approval_duration"] = string_to_delta(
514
section["approval_duration"])
515
client["checker_command"] = section["checker"]
516
client["last_approval_request"] = None
517
client["last_checked_ok"] = None
518
client["last_checker_status"] = -2
522
def __init__(self, settings, name = None):
524
# adding all client settings
525
for setting, value in settings.iteritems():
526
setattr(self, setting, value)
529
if not hasattr(self, "last_enabled"):
530
self.last_enabled = datetime.datetime.utcnow()
531
if not hasattr(self, "expires"):
532
self.expires = (datetime.datetime.utcnow()
535
self.last_enabled = None
376
538
logger.debug("Creating client %r", self.name)
377
539
# Uppercase and remove spaces from fingerprint for later
378
540
# comparison purposes with return value from the fingerprint()
380
self.fingerprint = (config["fingerprint"].upper()
382
542
logger.debug(" Fingerprint: %s", self.fingerprint)
383
if "secret" in config:
384
self.secret = config["secret"].decode("base64")
385
elif "secfile" in config:
386
with open(os.path.expanduser(os.path.expandvars
387
(config["secfile"])),
389
self.secret = secfile.read()
391
raise TypeError("No secret or secfile for client %s"
393
self.host = config.get("host", "")
394
self.created = datetime.datetime.utcnow()
396
self.last_approval_request = None
397
self.last_enabled = datetime.datetime.utcnow()
398
self.last_checked_ok = None
399
self.last_checker_status = None
400
self.timeout = string_to_delta(config["timeout"])
401
self.extended_timeout = string_to_delta(config
402
["extended_timeout"])
403
self.interval = string_to_delta(config["interval"])
543
self.created = settings.get("created",
544
datetime.datetime.utcnow())
546
# attributes specific for this server instance
404
547
self.checker = None
405
548
self.checker_initiator_tag = None
406
549
self.disable_initiator_tag = None
407
self.expires = datetime.datetime.utcnow() + self.timeout
408
550
self.checker_callback_tag = None
409
self.checker_command = config["checker"]
410
551
self.current_checker_command = None
411
self._approved = None
412
self.approved_by_default = config.get("approved_by_default",
414
553
self.approvals_pending = 0
415
self.approval_delay = string_to_delta(
416
config["approval_delay"])
417
self.approval_duration = string_to_delta(
418
config["approval_duration"])
419
554
self.changedstate = (multiprocessing_manager
420
555
.Condition(multiprocessing_manager
422
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
557
self.client_structure = [attr for attr in
558
self.__dict__.iterkeys()
559
if not attr.startswith("_")]
423
560
self.client_structure.append("client_structure")
425
562
for name, t in inspect.getmembers(type(self),
426
lambda obj: isinstance(obj, property)):
427
566
if not name.startswith("_"):
428
567
self.client_structure.append(name)
602
739
logger.debug("Stopping checker for %(name)s", vars(self))
604
os.kill(self.checker.pid, signal.SIGTERM)
741
self.checker.terminate()
606
743
#if self.checker.poll() is None:
607
# os.kill(self.checker.pid, signal.SIGKILL)
744
# self.checker.kill()
608
745
except OSError as error:
609
746
if error.errno != errno.ESRCH: # No such process
611
748
self.checker = None
613
# Encrypts a client secret and stores it in a varible encrypted_secret
614
def encrypt_secret(self, key):
615
# Encryption-key need to be of a specific size, so we hash inputed key
616
hasheng = hashlib.sha256()
618
encryptionkey = hasheng.digest()
620
# Create validation hash so we know at decryption if it was sucessful
621
hasheng = hashlib.sha256()
622
hasheng.update(self.secret)
623
validationhash = hasheng.digest()
626
iv = os.urandom(Crypto.Cipher.AES.block_size)
627
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
628
Crypto.Cipher.AES.MODE_CFB, iv)
629
ciphertext = ciphereng.encrypt(validationhash+self.secret)
630
self.encrypted_secret = (ciphertext, iv)
632
# Decrypt a encrypted client secret
633
def decrypt_secret(self, key):
634
# Decryption-key need to be of a specific size, so we hash inputed key
635
hasheng = hashlib.sha256()
637
encryptionkey = hasheng.digest()
639
# Decrypt encrypted secret
640
ciphertext, iv = self.encrypted_secret
641
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
642
Crypto.Cipher.AES.MODE_CFB, iv)
643
plain = ciphereng.decrypt(ciphertext)
645
# Validate decrypted secret to know if it was succesful
646
hasheng = hashlib.sha256()
647
validationhash = plain[:hasheng.digest_size]
648
secret = plain[hasheng.digest_size:]
649
hasheng.update(secret)
651
# if validation fails, we use key as new secret. Otherwhise, we use
652
# the decrypted secret
653
if hasheng.digest() == validationhash:
657
del self.encrypted_secret
660
751
def dbus_service_property(dbus_interface, signature="v",
814
954
e.setAttribute("access", prop._dbus_access)
816
956
for if_tag in document.getElementsByTagName("interface"):
817
958
for tag in (make_tag(document, name, prop)
819
in self._get_all_dbus_properties()
960
in self._get_all_dbus_things("property")
820
961
if prop._dbus_interface
821
962
== if_tag.getAttribute("name")):
822
963
if_tag.appendChild(tag)
964
# Add annotation tags
965
for typ in ("method", "signal", "property"):
966
for tag in if_tag.getElementsByTagName(typ):
968
for name, prop in (self.
969
_get_all_dbus_things(typ)):
970
if (name == tag.getAttribute("name")
971
and prop._dbus_interface
972
== if_tag.getAttribute("name")):
973
annots.update(getattr
977
for name, value in annots.iteritems():
978
ann_tag = document.createElement(
980
ann_tag.setAttribute("name", name)
981
ann_tag.setAttribute("value", value)
982
tag.appendChild(ann_tag)
983
# Add interface annotation tags
984
for annotation, value in dict(
985
itertools.chain.from_iterable(
986
annotations().iteritems()
987
for name, annotations in
988
self._get_all_dbus_things("interface")
989
if name == if_tag.getAttribute("name")
991
ann_tag = document.createElement("annotation")
992
ann_tag.setAttribute("name", annotation)
993
ann_tag.setAttribute("value", value)
994
if_tag.appendChild(ann_tag)
823
995
# Add the names to the return values for the
824
996
# "org.freedesktop.DBus.Properties" methods
825
997
if (if_tag.getAttribute("name")
852
1024
variant_level=variant_level)
855
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
857
"""Applied to an empty subclass of a D-Bus object, this metaclass
858
will add additional D-Bus attributes matching a certain pattern.
1027
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1028
"""A class decorator; applied to a subclass of
1029
dbus.service.Object, it will add alternate D-Bus attributes with
1030
interface names according to the "alt_interface_names" mapping.
1033
@alternate_dbus_interfaces({"org.example.Interface":
1034
"net.example.AlternateInterface"})
1035
class SampleDBusObject(dbus.service.Object):
1036
@dbus.service.method("org.example.Interface")
1037
def SampleDBusMethod():
1040
The above "SampleDBusMethod" on "SampleDBusObject" will be
1041
reachable via two interfaces: "org.example.Interface" and
1042
"net.example.AlternateInterface", the latter of which will have
1043
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1044
"true", unless "deprecate" is passed with a False value.
1046
This works for methods and signals, and also for D-Bus properties
1047
(from DBusObjectWithProperties) and interfaces (from the
1048
dbus_interface_annotations decorator).
860
def __new__(mcs, name, bases, attr):
861
# Go through all the base classes which could have D-Bus
862
# methods, signals, or properties in them
863
for base in (b for b in bases
864
if issubclass(b, dbus.service.Object)):
865
# Go though all attributes of the base class
866
for attrname, attribute in inspect.getmembers(base):
1051
for orig_interface_name, alt_interface_name in (
1052
alt_interface_names.iteritems()):
1054
interface_names = set()
1055
# Go though all attributes of the class
1056
for attrname, attribute in inspect.getmembers(cls):
867
1057
# Ignore non-D-Bus attributes, and D-Bus attributes
868
1058
# with the wrong interface name
869
1059
if (not hasattr(attribute, "_dbus_interface")
870
1060
or not attribute._dbus_interface
871
.startswith("se.recompile.Mandos")):
1061
.startswith(orig_interface_name)):
873
1063
# Create an alternate D-Bus interface name based on
874
1064
# the current name
875
1065
alt_interface = (attribute._dbus_interface
876
.replace("se.recompile.Mandos",
877
"se.bsnet.fukt.Mandos"))
1066
.replace(orig_interface_name,
1067
alt_interface_name))
1068
interface_names.add(alt_interface)
878
1069
# Is this a D-Bus signal?
879
1070
if getattr(attribute, "_dbus_is_signal", False):
880
1071
# Extract the original non-method function by
947
1150
attribute.func_name,
948
1151
attribute.func_defaults,
949
1152
attribute.func_closure)))
950
return type.__new__(mcs, name, bases, attr)
1153
# Copy annotations, if any
1155
attr[attrname]._dbus_annotations = (
1156
dict(attribute._dbus_annotations))
1157
except AttributeError:
1159
# Is this a D-Bus interface?
1160
elif getattr(attribute, "_dbus_is_interface", False):
1161
# Create a new, but exactly alike, function
1162
# object. Decorate it to be a new D-Bus interface
1163
# with the alternate D-Bus interface name. Add it
1165
attr[attrname] = (dbus_interface_annotations
1168
(attribute.func_code,
1169
attribute.func_globals,
1170
attribute.func_name,
1171
attribute.func_defaults,
1172
attribute.func_closure)))
1174
# Deprecate all alternate interfaces
1175
iname="_AlternateDBusNames_interface_annotation{0}"
1176
for interface_name in interface_names:
1177
@dbus_interface_annotations(interface_name)
1179
return { "org.freedesktop.DBus.Deprecated":
1181
# Find an unused name
1182
for aname in (iname.format(i)
1183
for i in itertools.count()):
1184
if aname not in attr:
1188
# Replace the class with a new subclass of it with
1189
# methods, signals, etc. as created above.
1190
cls = type(b"{0}Alternate".format(cls.__name__),
1196
@alternate_dbus_interfaces({"se.recompile.Mandos":
1197
"se.bsnet.fukt.Mandos"})
953
1198
class ClientDBus(Client, DBusObjectWithProperties):
954
1199
"""A Client class using D-Bus
1019
1261
checker is not None)
1020
1262
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1021
1263
"LastCheckedOK")
1264
last_checker_status = notifychangeproperty(dbus.Int16,
1265
"LastCheckerStatus")
1022
1266
last_approval_request = notifychangeproperty(
1023
1267
datetime_to_dbus, "LastApprovalRequest")
1024
1268
approved_by_default = notifychangeproperty(dbus.Boolean,
1025
1269
"ApprovedByDefault")
1026
approval_delay = notifychangeproperty(dbus.UInt16,
1270
approval_delay = notifychangeproperty(dbus.UInt64,
1027
1271
"ApprovalDelay",
1029
_timedelta_to_milliseconds)
1273
timedelta_to_milliseconds)
1030
1274
approval_duration = notifychangeproperty(
1031
dbus.UInt16, "ApprovalDuration",
1032
type_func = _timedelta_to_milliseconds)
1275
dbus.UInt64, "ApprovalDuration",
1276
type_func = timedelta_to_milliseconds)
1033
1277
host = notifychangeproperty(dbus.String, "Host")
1034
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1278
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1036
_timedelta_to_milliseconds)
1280
timedelta_to_milliseconds)
1037
1281
extended_timeout = notifychangeproperty(
1038
dbus.UInt16, "ExtendedTimeout",
1039
type_func = _timedelta_to_milliseconds)
1040
interval = notifychangeproperty(dbus.UInt16,
1282
dbus.UInt64, "ExtendedTimeout",
1283
type_func = timedelta_to_milliseconds)
1284
interval = notifychangeproperty(dbus.UInt64,
1043
_timedelta_to_milliseconds)
1287
timedelta_to_milliseconds)
1044
1288
checker_command = notifychangeproperty(dbus.String, "Checker")
1046
1290
del notifychangeproperty
1659
1899
use_ipv6: Boolean; to use IPv6 or not
1661
1901
def __init__(self, server_address, RequestHandlerClass,
1662
interface=None, use_ipv6=True):
1902
interface=None, use_ipv6=True, socketfd=None):
1903
"""If socketfd is set, use that file descriptor instead of
1904
creating a new one with socket.socket().
1663
1906
self.interface = interface
1665
1908
self.address_family = socket.AF_INET6
1909
if socketfd is not None:
1910
# Save the file descriptor
1911
self.socketfd = socketfd
1912
# Save the original socket.socket() function
1913
self.socket_socket = socket.socket
1914
# To implement --socket, we monkey patch socket.socket.
1916
# (When socketserver.TCPServer is a new-style class, we
1917
# could make self.socket into a property instead of monkey
1918
# patching socket.socket.)
1920
# Create a one-time-only replacement for socket.socket()
1921
@functools.wraps(socket.socket)
1922
def socket_wrapper(*args, **kwargs):
1923
# Restore original function so subsequent calls are
1925
socket.socket = self.socket_socket
1926
del self.socket_socket
1927
# This time only, return a new socket object from the
1928
# saved file descriptor.
1929
return socket.fromfd(self.socketfd, *args, **kwargs)
1930
# Replace socket.socket() function with wrapper
1931
socket.socket = socket_wrapper
1932
# The socketserver.TCPServer.__init__ will call
1933
# socket.socket(), which might be our replacement,
1934
# socket_wrapper(), if socketfd was set.
1666
1935
socketserver.TCPServer.__init__(self, server_address,
1667
1936
RequestHandlerClass)
1668
1938
def server_bind(self):
1669
1939
"""This overrides the normal server_bind() function
1670
1940
to bind to an interface if one was specified, and also NOT to
1963
2233
# Convert the SafeConfigParser object to a dict
1964
2234
server_settings = server_config.defaults()
1965
2235
# Use the appropriate methods on the non-string config options
1966
for option in ("debug", "use_dbus", "use_ipv6"):
2236
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
1967
2237
server_settings[option] = server_config.getboolean("DEFAULT",
1969
2239
if server_settings["port"]:
1970
2240
server_settings["port"] = server_config.getint("DEFAULT",
2242
if server_settings["socket"]:
2243
server_settings["socket"] = server_config.getint("DEFAULT",
2245
# Later, stdin will, and stdout and stderr might, be dup'ed
2246
# over with an opened os.devnull. But we don't want this to
2247
# happen with a supplied network socket.
2248
if 0 <= server_settings["socket"] <= 2:
2249
server_settings["socket"] = os.dup(server_settings
1972
2251
del server_config
1974
2253
# Override the settings from the config file with command line
1975
2254
# options, if set.
1976
2255
for option in ("interface", "address", "port", "debug",
1977
2256
"priority", "servicename", "configdir",
1978
"use_dbus", "use_ipv6", "debuglevel", "restore"):
2257
"use_dbus", "use_ipv6", "debuglevel", "restore",
2258
"statedir", "socket", "foreground"):
1979
2259
value = getattr(options, option)
1980
2260
if value is not None:
1981
2261
server_settings[option] = value
2123
2404
client_class = Client
2125
client_class = functools.partial(ClientDBusTransitional,
2128
special_settings = {
2129
# Some settings need to be accessd by special methods;
2130
# booleans need .getboolean(), etc. Here is a list of them:
2131
"approved_by_default":
2133
client_config.getboolean(section, "approved_by_default"),
2135
# Construct a new dict of client settings of this form:
2136
# { client_name: {setting_name: value, ...}, ...}
2137
# with exceptions for any special settings as defined above
2138
client_settings = dict((clientname,
2140
(value if setting not in special_settings
2141
else special_settings[setting](clientname)))
2142
for setting, value in client_config.items(clientname)))
2143
for clientname in client_config.sections())
2406
client_class = functools.partial(ClientDBus, bus = bus)
2408
client_settings = Client.config_parser(client_config)
2145
2409
old_client_settings = {}
2148
# Get client data and settings from last running state.
2412
# Get client data and settings from last running state.
2149
2413
if server_settings["restore"]:
2151
2415
with open(stored_state_path, "rb") as stored_state:
2152
clients_data, old_client_settings = pickle.load(stored_state)
2416
clients_data, old_client_settings = (pickle.load
2153
2418
os.remove(stored_state_path)
2154
2419
except IOError as e:
2155
logger.warning("Could not load persistant state: {0}".format(e))
2156
if e.errno != errno.ENOENT:
2420
if e.errno == errno.ENOENT:
2421
logger.warning("Could not load persistent state: {0}"
2422
.format(os.strerror(e.errno)))
2424
logger.critical("Could not load persistent state:",
2427
except EOFError as e:
2428
logger.warning("Could not load persistent state: "
2429
"EOFError:", exc_info=e)
2159
for client in clients_data:
2160
client_name = client["name"]
2162
# Decide which value to use after restoring saved state.
2163
# We have three different values: Old config file,
2164
# new config file, and saved state.
2165
# New config value takes precedence if it differs from old
2166
# config value, otherwise use saved state.
2167
for name, value in client_settings[client_name].items():
2431
with PGPEngine() as pgp:
2432
for client_name, client in clients_data.iteritems():
2433
# Decide which value to use after restoring saved state.
2434
# We have three different values: Old config file,
2435
# new config file, and saved state.
2436
# New config value takes precedence if it differs from old
2437
# config value, otherwise use saved state.
2438
for name, value in client_settings[client_name].items():
2440
# For each value in new config, check if it
2441
# differs from the old config value (Except for
2442
# the "secret" attribute)
2443
if (name != "secret" and
2444
value != old_client_settings[client_name]
2446
client[name] = value
2450
# Clients who has passed its expire date can still be
2451
# enabled if its last checker was successful. Clients
2452
# whose checker succeeded before we stored its state is
2453
# assumed to have successfully run all checkers during
2455
if client["enabled"]:
2456
if datetime.datetime.utcnow() >= client["expires"]:
2457
if not client["last_checked_ok"]:
2459
"disabling client {0} - Client never "
2460
"performed a successful checker"
2461
.format(client_name))
2462
client["enabled"] = False
2463
elif client["last_checker_status"] != 0:
2465
"disabling client {0} - Client "
2466
"last checker failed with error code {1}"
2467
.format(client_name,
2468
client["last_checker_status"]))
2469
client["enabled"] = False
2471
client["expires"] = (datetime.datetime
2473
+ client["timeout"])
2474
logger.debug("Last checker succeeded,"
2475
" keeping {0} enabled"
2476
.format(client_name))
2169
# For each value in new config, check if it differs
2170
# from the old config value (Except for the "secret"
2172
if name != "secret" and value != old_client_settings[client_name][name]:
2173
setattr(client, name, value)
2177
# Clients who has passed its expire date, can still be enabled if its
2178
# last checker was sucessful. Clients who checkers failed before we
2179
# stored it state is asumed to had failed checker during downtime.
2180
if client["enabled"] and client["last_checked_ok"]:
2181
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2182
> client["interval"]):
2183
if client["last_checker_status"] != 0:
2184
client["enabled"] = False
2186
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2188
client["changedstate"] = (multiprocessing_manager
2189
.Condition(multiprocessing_manager
2192
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2193
tcp_server.clients[client_name] = new_client
2194
new_client.bus = bus
2195
for name, value in client.iteritems():
2196
setattr(new_client, name, value)
2197
client_object_name = unicode(client_name).translate(
2198
{ord("."): ord("_"),
2199
ord("-"): ord("_")})
2200
new_client.dbus_object_path = (dbus.ObjectPath
2201
("/clients/" + client_object_name))
2202
DBusObjectWithProperties.__init__(new_client,
2204
new_client.dbus_object_path)
2206
tcp_server.clients[client_name] = Client.__new__(Client)
2207
for name, value in client.iteritems():
2208
setattr(tcp_server.clients[client_name], name, value)
2210
tcp_server.clients[client_name].decrypt_secret(
2211
client_settings[client_name]["secret"])
2213
# Create/remove clients based on new changes made to config
2214
for clientname in set(old_client_settings) - set(client_settings):
2215
del tcp_server.clients[clientname]
2216
for clientname in set(client_settings) - set(old_client_settings):
2217
tcp_server.clients[clientname] = (client_class(name = clientname,
2478
client["secret"] = (
2479
pgp.decrypt(client["encrypted_secret"],
2480
client_settings[client_name]
2483
# If decryption fails, we use secret from new settings
2484
logger.debug("Failed to decrypt {0} old secret"
2485
.format(client_name))
2486
client["secret"] = (
2487
client_settings[client_name]["secret"])
2489
# Add/remove clients based on new changes made to config
2490
for client_name in (set(old_client_settings)
2491
- set(client_settings)):
2492
del clients_data[client_name]
2493
for client_name in (set(client_settings)
2494
- set(old_client_settings)):
2495
clients_data[client_name] = client_settings[client_name]
2497
# Create all client objects
2498
for client_name, client in clients_data.iteritems():
2499
tcp_server.clients[client_name] = client_class(
2500
name = client_name, settings = client)
2223
2502
if not tcp_server.clients:
2224
2503
logger.warning("No clients defined")
2230
pidfile.write(str(pid) + "\n".encode("utf-8"))
2233
logger.error("Could not write to file %r with PID %d",
2236
# "pidfile" was never created
2506
if pidfile is not None:
2510
pidfile.write(str(pid) + "\n".encode("utf-8"))
2512
logger.error("Could not write to file %r with PID %d",
2238
2515
del pidfilename
2240
signal.signal(signal.SIGINT, signal.SIG_IGN)
2242
2517
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2243
2518
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2246
class MandosDBusService(dbus.service.Object):
2521
@alternate_dbus_interfaces({"se.recompile.Mandos":
2522
"se.bsnet.fukt.Mandos"})
2523
class MandosDBusService(DBusObjectWithProperties):
2247
2524
"""A D-Bus proxy object"""
2248
2525
def __init__(self):
2249
2526
dbus.service.Object.__init__(self, bus, "/")
2250
2527
_interface = "se.recompile.Mandos"
2529
@dbus_interface_annotations(_interface)
2531
return { "org.freedesktop.DBus.Property"
2532
".EmitsChangedSignal":
2252
2535
@dbus.service.signal(_interface, signature="o")
2253
2536
def ClientAdded(self, objpath):
2308
2589
if not (tcp_server.clients or client_settings):
2311
# Store client before exiting. Secrets are encrypted with key based
2312
# on what config file has. If config file is removed/edited, old
2313
# secret will thus be unrecovable.
2315
for client in tcp_server.clients.itervalues():
2316
client.encrypt_secret(client_settings[client.name]["secret"])
2320
# A list of attributes that will not be stored when shuting down.
2321
exclude = set(("bus", "changedstate", "secret"))
2322
for name, typ in inspect.getmembers(dbus.service.Object):
2325
client_dict["encrypted_secret"] = client.encrypted_secret
2326
for attr in client.client_structure:
2327
if attr not in exclude:
2328
client_dict[attr] = getattr(client, attr)
2330
clients.append(client_dict)
2331
del client_settings[client.name]["secret"]
2592
# Store client before exiting. Secrets are encrypted with key
2593
# based on what config file has. If config file is
2594
# removed/edited, old secret will thus be unrecovable.
2596
with PGPEngine() as pgp:
2597
for client in tcp_server.clients.itervalues():
2598
key = client_settings[client.name]["secret"]
2599
client.encrypted_secret = pgp.encrypt(client.secret,
2603
# A list of attributes that can not be pickled
2605
exclude = set(("bus", "changedstate", "secret",
2607
for name, typ in (inspect.getmembers
2608
(dbus.service.Object)):
2611
client_dict["encrypted_secret"] = (client
2613
for attr in client.client_structure:
2614
if attr not in exclude:
2615
client_dict[attr] = getattr(client, attr)
2617
clients[client.name] = client_dict
2618
del client_settings[client.name]["secret"]
2334
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2621
with (tempfile.NamedTemporaryFile
2622
(mode='wb', suffix=".pickle", prefix='clients-',
2623
dir=os.path.dirname(stored_state_path),
2624
delete=False)) as stored_state:
2335
2625
pickle.dump((clients, client_settings), stored_state)
2336
except IOError as e:
2337
logger.warning("Could not save persistant state: {0}".format(e))
2338
if e.errno != errno.ENOENT:
2626
tempname=stored_state.name
2627
os.rename(tempname, stored_state_path)
2628
except (IOError, OSError) as e:
2634
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2635
logger.warning("Could not save persistent state: {0}"
2636
.format(os.strerror(e.errno)))
2638
logger.warning("Could not save persistent state:",
2341
2642
# Delete all clients, and settings from config
2342
2643
while tcp_server.clients: