84
88
except ImportError:
85
89
SO_BINDTODEVICE = None
92
stored_state_file = "clients.pickle"
90
94
logger = logging.getLogger()
91
stored_state_path = "/var/lib/mandos/clients.pickle"
93
95
syslogger = (logging.handlers.SysLogHandler
94
96
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
97
address = str("/dev/log")))
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)
100
if_nametoindex = (ctypes.cdll.LoadLibrary
101
(ctypes.util.find_library("c"))
103
except (OSError, AttributeError):
104
def if_nametoindex(interface):
105
"Get an interface index the hard way, i.e. using fcntl()"
106
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
107
with contextlib.closing(socket.socket()) as s:
108
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
113
return interface_index
116
def initlogger(debug, level=logging.WARNING):
117
"""init logger and add loglevel"""
119
syslogger.setFormatter(logging.Formatter
120
('Mandos [%(process)d]: %(levelname)s:'
122
logger.addHandler(syslogger)
125
console = logging.StreamHandler()
126
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
130
logger.addHandler(console)
131
logger.setLevel(level)
134
class PGPError(Exception):
135
"""Exception if encryption/decryption fails"""
139
class PGPEngine(object):
140
"""A simple class for OpenPGP symmetric encryption & decryption"""
142
self.gnupg = GnuPGInterface.GnuPG()
143
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
144
self.gnupg = GnuPGInterface.GnuPG()
145
self.gnupg.options.meta_interactive = False
146
self.gnupg.options.homedir = self.tempdir
147
self.gnupg.options.extra_args.extend(['--force-mdc',
154
def __exit__(self, exc_type, exc_value, traceback):
162
if self.tempdir is not None:
163
# Delete contents of tempdir
164
for root, dirs, files in os.walk(self.tempdir,
166
for filename in files:
167
os.remove(os.path.join(root, filename))
169
os.rmdir(os.path.join(root, dirname))
171
os.rmdir(self.tempdir)
174
def password_encode(self, password):
175
# Passphrase can not be empty and can not contain newlines or
176
# NUL bytes. So we prefix it and hex encode it.
177
return b"mandos" + binascii.hexlify(password)
179
def encrypt(self, data, password):
180
self.gnupg.passphrase = self.password_encode(password)
181
with open(os.devnull, "w") as devnull:
183
proc = self.gnupg.run(['--symmetric'],
184
create_fhs=['stdin', 'stdout'],
185
attach_fhs={'stderr': devnull})
186
with contextlib.closing(proc.handles['stdin']) as f:
188
with contextlib.closing(proc.handles['stdout']) as f:
189
ciphertext = f.read()
193
self.gnupg.passphrase = None
196
def decrypt(self, data, password):
197
self.gnupg.passphrase = self.password_encode(password)
198
with open(os.devnull, "w") as devnull:
200
proc = self.gnupg.run(['--decrypt'],
201
create_fhs=['stdin', 'stdout'],
202
attach_fhs={'stderr': devnull})
203
with contextlib.closing(proc.handles['stdin']) as f:
205
with contextlib.closing(proc.handles['stdout']) as f:
206
decrypted_plaintext = f.read()
210
self.gnupg.passphrase = None
211
return decrypted_plaintext
109
214
class AvahiError(Exception):
311
427
last_approval_request: datetime.datetime(); (UTC) or None
312
428
last_checked_ok: datetime.datetime(); (UTC) or None
313
429
last_checker_status: integer between 0 and 255 reflecting exit
314
status of last checker. -1 reflect crashed
316
last_enabled: datetime.datetime(); (UTC)
430
status of last checker. -1 reflects crashed
431
checker, -2 means no checker completed yet.
432
last_enabled: datetime.datetime(); (UTC) or None
317
433
name: string; from the config file, used in log messages and
318
434
D-Bus identifiers
319
435
secret: bytestring; sent verbatim (over TLS) to client
320
436
timeout: datetime.timedelta(); How long from last_checked_ok
321
437
until this client is disabled
322
extended_timeout: extra long timeout when password has been sent
438
extended_timeout: extra long timeout when secret has been sent
323
439
runtime_expansions: Allowed attributes for runtime expansion.
324
440
expires: datetime.datetime(); time (UTC) when a client will be
325
441
disabled, or None
328
444
runtime_expansions = ("approval_delay", "approval_duration",
329
"created", "enabled", "fingerprint",
330
"host", "interval", "last_checked_ok",
445
"created", "enabled", "expires",
446
"fingerprint", "host", "interval",
447
"last_approval_request", "last_checked_ok",
331
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",
333
460
def timeout_milliseconds(self):
334
461
"Return the 'timeout' attribute in milliseconds"
335
return _timedelta_to_milliseconds(self.timeout)
462
return timedelta_to_milliseconds(self.timeout)
337
464
def extended_timeout_milliseconds(self):
338
465
"Return the 'extended_timeout' attribute in milliseconds"
339
return _timedelta_to_milliseconds(self.extended_timeout)
466
return timedelta_to_milliseconds(self.extended_timeout)
341
468
def interval_milliseconds(self):
342
469
"Return the 'interval' attribute in milliseconds"
343
return _timedelta_to_milliseconds(self.interval)
470
return timedelta_to_milliseconds(self.interval)
345
472
def approval_delay_milliseconds(self):
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'
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
355
538
logger.debug("Creating client %r", self.name)
356
539
# Uppercase and remove spaces from fingerprint for later
357
540
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
361
542
logger.debug(" Fingerprint: %s", self.fingerprint)
362
if "secret" in config:
363
self.secret = config["secret"].decode("base64")
364
elif "secfile" in config:
365
with open(os.path.expanduser(os.path.expandvars
366
(config["secfile"])),
368
self.secret = secfile.read()
370
raise TypeError("No secret or secfile for client %s"
372
self.host = config.get("host", "")
373
self.created = datetime.datetime.utcnow()
375
self.last_approval_request = None
376
self.last_enabled = datetime.datetime.utcnow()
377
self.last_checked_ok = None
378
self.last_checker_status = None
379
self.timeout = string_to_delta(config["timeout"])
380
self.extended_timeout = string_to_delta(config
381
["extended_timeout"])
382
self.interval = string_to_delta(config["interval"])
543
self.created = settings.get("created",
544
datetime.datetime.utcnow())
546
# attributes specific for this server instance
383
547
self.checker = None
384
548
self.checker_initiator_tag = None
385
549
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
387
550
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
389
551
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
393
553
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"])
398
554
self.changedstate = (multiprocessing_manager
399
555
.Condition(multiprocessing_manager
401
self.client_structure = [attr for attr
402
in self.__dict__.iterkeys()
557
self.client_structure = [attr for attr in
558
self.__dict__.iterkeys()
403
559
if not attr.startswith("_")]
404
560
self.client_structure.append("client_structure")
407
562
for name, t in inspect.getmembers(type(self),
421
576
if getattr(self, "enabled", False):
422
577
# Already enabled
424
self.send_changedstate()
425
579
self.expires = datetime.datetime.utcnow() + self.timeout
426
580
self.enabled = True
427
581
self.last_enabled = datetime.datetime.utcnow()
428
582
self.init_checker()
583
self.send_changedstate()
430
585
def disable(self, quiet=True):
431
586
"""Disable this client."""
432
587
if not getattr(self, "enabled", False):
435
self.send_changedstate()
437
590
logger.info("Disabling client %s", self.name)
438
if getattr(self, "disable_initiator_tag", False):
591
if getattr(self, "disable_initiator_tag", None) is not None:
439
592
gobject.source_remove(self.disable_initiator_tag)
440
593
self.disable_initiator_tag = None
441
594
self.expires = None
442
if getattr(self, "checker_initiator_tag", False):
595
if getattr(self, "checker_initiator_tag", None) is not None:
443
596
gobject.source_remove(self.checker_initiator_tag)
444
597
self.checker_initiator_tag = None
445
598
self.stop_checker()
446
599
self.enabled = False
601
self.send_changedstate()
447
602
# Do not run this again if called by a gobject.timeout_add
450
605
def __del__(self):
453
608
def init_checker(self):
454
609
# Schedule a new checker to be started an 'interval' from now,
455
610
# and every interval from then on.
611
if self.checker_initiator_tag is not None:
612
gobject.source_remove(self.checker_initiator_tag)
456
613
self.checker_initiator_tag = (gobject.timeout_add
457
614
(self.interval_milliseconds(),
458
615
self.start_checker))
459
616
# Schedule a disable() when 'timeout' has passed
617
if self.disable_initiator_tag is not None:
618
gobject.source_remove(self.disable_initiator_tag)
460
619
self.disable_initiator_tag = (gobject.timeout_add
461
620
(self.timeout_milliseconds(),
463
622
# Also start a new checker *right now*.
464
623
self.start_checker()
467
625
def checker_callback(self, pid, condition, command):
468
626
"""The checker has completed, so take appropriate actions."""
469
627
self.checker_callback_tag = None
470
628
self.checker = None
471
629
if os.WIFEXITED(condition):
472
self.last_checker_status = os.WEXITSTATUS(condition)
630
self.last_checker_status = os.WEXITSTATUS(condition)
473
631
if self.last_checker_status == 0:
474
632
logger.info("Checker for %(name)s succeeded",
587
739
logger.debug("Stopping checker for %(name)s", vars(self))
589
os.kill(self.checker.pid, signal.SIGTERM)
741
self.checker.terminate()
591
743
#if self.checker.poll() is None:
592
# os.kill(self.checker.pid, signal.SIGKILL)
744
# self.checker.kill()
593
745
except OSError as error:
594
746
if error.errno != errno.ESRCH: # No such process
596
748
self.checker = None
598
# Encrypts a client secret and stores it in a varible
600
def encrypt_secret(self, key):
601
# Encryption-key need to be of a specific size, so we hash
603
hasheng = hashlib.sha256()
605
encryptionkey = hasheng.digest()
607
# Create validation hash so we know at decryption if it was
609
hasheng = hashlib.sha256()
610
hasheng.update(self.secret)
611
validationhash = hasheng.digest()
614
iv = os.urandom(Crypto.Cipher.AES.block_size)
615
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
616
Crypto.Cipher.AES.MODE_CFB, iv)
617
ciphertext = ciphereng.encrypt(validationhash+self.secret)
618
self.encrypted_secret = (ciphertext, iv)
620
# Decrypt a encrypted client secret
621
def decrypt_secret(self, key):
622
# Decryption-key need to be of a specific size, so we hash
624
hasheng = hashlib.sha256()
626
encryptionkey = hasheng.digest()
628
# Decrypt encrypted secret
629
ciphertext, iv = self.encrypted_secret
630
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
631
Crypto.Cipher.AES.MODE_CFB, iv)
632
plain = ciphereng.decrypt(ciphertext)
634
# Validate decrypted secret to know if it was succesful
635
hasheng = hashlib.sha256()
636
validationhash = plain[:hasheng.digest_size]
637
secret = plain[hasheng.digest_size:]
638
hasheng.update(secret)
640
# If validation fails, we use key as new secret. Otherwise, we
641
# use the decrypted secret
642
if hasheng.digest() == validationhash:
646
del self.encrypted_secret
649
751
def dbus_service_property(dbus_interface, signature="v",
650
752
access="readwrite", byte_arrays=False):
803
954
e.setAttribute("access", prop._dbus_access)
805
956
for if_tag in document.getElementsByTagName("interface"):
806
958
for tag in (make_tag(document, name, prop)
808
in self._get_all_dbus_properties()
960
in self._get_all_dbus_things("property")
809
961
if prop._dbus_interface
810
962
== if_tag.getAttribute("name")):
811
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)
812
995
# Add the names to the return values for the
813
996
# "org.freedesktop.DBus.Properties" methods
814
997
if (if_tag.getAttribute("name")
829
1012
except (AttributeError, xml.dom.DOMException,
830
1013
xml.parsers.expat.ExpatError) as error:
831
1014
logger.error("Failed to override Introspection method",
833
1016
return xmlstring
836
def datetime_to_dbus (dt, variant_level=0):
1019
def datetime_to_dbus(dt, variant_level=0):
837
1020
"""Convert a UTC datetime.datetime() to a D-Bus type."""
839
1022
return dbus.String("", variant_level = variant_level)
840
1023
return dbus.String(dt.isoformat(),
841
1024
variant_level=variant_level)
843
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
845
"""Applied to an empty subclass of a D-Bus object, this metaclass
846
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).
848
def __new__(mcs, name, bases, attr):
849
# Go through all the base classes which could have D-Bus
850
# methods, signals, or properties in them
851
for base in (b for b in bases
852
if issubclass(b, dbus.service.Object)):
853
# Go though all attributes of the base class
854
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):
855
1057
# Ignore non-D-Bus attributes, and D-Bus attributes
856
1058
# with the wrong interface name
857
1059
if (not hasattr(attribute, "_dbus_interface")
858
1060
or not attribute._dbus_interface
859
.startswith("se.recompile.Mandos")):
1061
.startswith(orig_interface_name)):
861
1063
# Create an alternate D-Bus interface name based on
862
1064
# the current name
863
1065
alt_interface = (attribute._dbus_interface
864
.replace("se.recompile.Mandos",
865
"se.bsnet.fukt.Mandos"))
1066
.replace(orig_interface_name,
1067
alt_interface_name))
1068
interface_names.add(alt_interface)
866
1069
# Is this a D-Bus signal?
867
1070
if getattr(attribute, "_dbus_is_signal", False):
868
1071
# Extract the original non-method function by
935
1150
attribute.func_name,
936
1151
attribute.func_defaults,
937
1152
attribute.func_closure)))
938
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"})
940
1198
class ClientDBus(Client, DBusObjectWithProperties):
941
1199
"""A Client class using D-Bus
1635
1899
use_ipv6: Boolean; to use IPv6 or not
1637
1901
def __init__(self, server_address, RequestHandlerClass,
1638
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().
1639
1906
self.interface = interface
1641
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.
1642
1935
socketserver.TCPServer.__init__(self, server_address,
1643
1936
RequestHandlerClass)
1644
1938
def server_bind(self):
1645
1939
"""This overrides the normal server_bind() function
1646
1940
to bind to an interface if one was specified, and also NOT to
1840
2122
elif suffix == "w":
1841
2123
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1843
raise ValueError("Unknown suffix %r" % suffix)
2125
raise ValueError("Unknown suffix {0!r}"
1844
2127
except (ValueError, IndexError) as e:
1845
2128
raise ValueError(*(e.args))
1846
2129
timevalue += delta
1847
2130
return timevalue
1850
def if_nametoindex(interface):
1851
"""Call the C function if_nametoindex(), or equivalent
1853
Note: This function cannot accept a unicode string."""
1854
global if_nametoindex
1856
if_nametoindex = (ctypes.cdll.LoadLibrary
1857
(ctypes.util.find_library("c"))
1859
except (OSError, AttributeError):
1860
logger.warning("Doing if_nametoindex the hard way")
1861
def if_nametoindex(interface):
1862
"Get an interface index the hard way, i.e. using fcntl()"
1863
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1864
with contextlib.closing(socket.socket()) as s:
1865
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1866
struct.pack(str("16s16x"),
1868
interface_index = struct.unpack(str("I"),
1870
return interface_index
1871
return if_nametoindex(interface)
1874
2133
def daemon(nochdir = False, noclose = False):
1875
2134
"""See daemon(3). Standard BSD Unix function.
1964
2233
# Convert the SafeConfigParser object to a dict
1965
2234
server_settings = server_config.defaults()
1966
2235
# Use the appropriate methods on the non-string config options
1967
for option in ("debug", "use_dbus", "use_ipv6"):
2236
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
1968
2237
server_settings[option] = server_config.getboolean("DEFAULT",
1970
2239
if server_settings["port"]:
1971
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
1973
2251
del server_config
1975
2253
# Override the settings from the config file with command line
1976
2254
# options, if set.
1977
2255
for option in ("interface", "address", "port", "debug",
1978
2256
"priority", "servicename", "configdir",
1979
"use_dbus", "use_ipv6", "debuglevel", "restore"):
2257
"use_dbus", "use_ipv6", "debuglevel", "restore",
2258
"statedir", "socket", "foreground"):
1980
2259
value = getattr(options, option)
1981
2260
if value is not None:
1982
2261
server_settings[option] = value
2122
2404
client_class = Client
2124
client_class = functools.partial(ClientDBusTransitional,
2127
special_settings = {
2128
# Some settings need to be accessd by special methods;
2129
# booleans need .getboolean(), etc. Here is a list of them:
2130
"approved_by_default":
2132
client_config.getboolean(section, "approved_by_default"),
2134
# Construct a new dict of client settings of this form:
2135
# { client_name: {setting_name: value, ...}, ...}
2136
# with exceptions for any special settings as defined above
2137
client_settings = dict((clientname,
2140
setting not in special_settings
2141
else special_settings[setting]
2144
in client_config.items(clientname)))
2145
for clientname in client_config.sections())
2406
client_class = functools.partial(ClientDBus, bus = bus)
2408
client_settings = Client.config_parser(client_config)
2147
2409
old_client_settings = {}
2150
# Get client data and settings from last running state.
2412
# Get client data and settings from last running state.
2151
2413
if server_settings["restore"]:
2153
2415
with open(stored_state_path, "rb") as stored_state:
2154
clients_data, old_client_settings = (
2155
pickle.load(stored_state))
2416
clients_data, old_client_settings = (pickle.load
2156
2418
os.remove(stored_state_path)
2157
2419
except IOError as e:
2158
logger.warning("Could not load persistant state: {0}"
2160
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:",
2163
for client in clients_data:
2164
client_name = client["name"]
2166
# Decide which value to use after restoring saved state.
2167
# We have three different values: Old config file,
2168
# new config file, and saved state.
2169
# New config value takes precedence if it differs from old
2170
# config value, otherwise use saved state.
2171
for name, value in client_settings[client_name].items():
2427
except EOFError as e:
2428
logger.warning("Could not load persistent state: "
2429
"EOFError:", exc_info=e)
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))
2173
# For each value in new config, check if it differs
2174
# from the old config value (Except for the "secret"
2176
if (name != "secret" and
2177
value != old_client_settings[client_name][name]):
2178
setattr(client, name, value)
2182
# Clients who has passed its expire date, can still be enabled
2183
# if its last checker was sucessful. Clients who checkers
2184
# failed before we stored it state is asumed to had failed
2185
# checker during downtime.
2186
if client["enabled"] and client["last_checked_ok"]:
2187
if ((datetime.datetime.utcnow()
2188
- client["last_checked_ok"]) > client["interval"]):
2189
if client["last_checker_status"] != 0:
2190
client["enabled"] = False
2192
client["expires"] = (datetime.datetime.utcnow()
2193
+ client["timeout"])
2195
client["changedstate"] = (multiprocessing_manager
2196
.Condition(multiprocessing_manager
2199
new_client = ClientDBusTransitional.__new__(
2200
ClientDBusTransitional)
2201
tcp_server.clients[client_name] = new_client
2202
new_client.bus = bus
2203
for name, value in client.iteritems():
2204
setattr(new_client, name, value)
2205
new_client._approvals_pending = 0
2206
new_client.add_to_dbus()
2208
tcp_server.clients[client_name] = Client.__new__(Client)
2209
for name, value in client.iteritems():
2210
setattr(tcp_server.clients[client_name], name, value)
2212
tcp_server.clients[client_name].decrypt_secret(
2213
client_settings[client_name]["secret"])
2215
# Create/remove clients based on new changes made to config
2216
for clientname in set(old_client_settings) - set(client_settings):
2217
del tcp_server.clients[clientname]
2218
for clientname in set(client_settings) - set(old_client_settings):
2219
tcp_server.clients[clientname] = client_class(name
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)
2225
2502
if not tcp_server.clients:
2226
2503
logger.warning("No clients defined")
2232
pidfile.write(str(pid) + "\n".encode("utf-8"))
2235
logger.error("Could not write to file %r with PID %d",
2238
# "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",
2240
2515
del pidfilename
2242
signal.signal(signal.SIGINT, signal.SIG_IGN)
2244
2517
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2245
2518
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2248
class MandosDBusService(dbus.service.Object):
2521
@alternate_dbus_interfaces({"se.recompile.Mandos":
2522
"se.bsnet.fukt.Mandos"})
2523
class MandosDBusService(DBusObjectWithProperties):
2249
2524
"""A D-Bus proxy object"""
2250
2525
def __init__(self):
2251
2526
dbus.service.Object.__init__(self, bus, "/")
2252
2527
_interface = "se.recompile.Mandos"
2529
@dbus_interface_annotations(_interface)
2531
return { "org.freedesktop.DBus.Property"
2532
".EmitsChangedSignal":
2254
2535
@dbus.service.signal(_interface, signature="o")
2255
2536
def ClientAdded(self, objpath):
2309
2588
multiprocessing.active_children()
2310
2589
if not (tcp_server.clients or client_settings):
2313
2592
# Store client before exiting. Secrets are encrypted with key
2314
2593
# based on what config file has. If config file is
2315
2594
# removed/edited, old secret will thus be unrecovable.
2317
for client in tcp_server.clients.itervalues():
2318
client.encrypt_secret(
2319
client_settings[client.name]["secret"])
2323
# A list of attributes that will not be stored when
2325
exclude = set(("bus", "changedstate", "secret"))
2326
for name, typ in inspect.getmembers(dbus.service.Object):
2329
client_dict["encrypted_secret"] = client.encrypted_secret
2330
for attr in client.client_structure:
2331
if attr not in exclude:
2332
client_dict[attr] = getattr(client, attr)
2334
clients.append(client_dict)
2335
del client_settings[client.name]["secret"]
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"]
2338
with os.fdopen(os.open(stored_state_path,
2339
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2340
stat.S_IRUSR | stat.S_IWUSR),
2341
"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:
2342
2625
pickle.dump((clients, client_settings), stored_state)
2343
except IOError as e:
2344
logger.warning("Could not save persistant state: {0}"
2346
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:",
2349
2642
# Delete all clients, and settings from config
2350
2643
while tcp_server.clients:
2351
2644
name, client = tcp_server.clients.popitem()