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.tempdir = tempfile.mkdtemp(prefix="mandos-")
143
self.gnupgargs = ['--batch',
144
'--home', self.tempdir,
152
def __exit__(self, exc_type, exc_value, traceback):
160
if self.tempdir is not None:
161
# Delete contents of tempdir
162
for root, dirs, files in os.walk(self.tempdir,
164
for filename in files:
165
os.remove(os.path.join(root, filename))
167
os.rmdir(os.path.join(root, dirname))
169
os.rmdir(self.tempdir)
172
def password_encode(self, password):
173
# Passphrase can not be empty and can not contain newlines or
174
# NUL bytes. So we prefix it and hex encode it.
175
encoded = b"mandos" + binascii.hexlify(password)
176
if len(encoded) > 2048:
177
# GnuPG can't handle long passwords, so encode differently
178
encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
179
.replace(b"\n", b"\\n")
180
.replace(b"\0", b"\\x00"))
183
def encrypt(self, data, password):
184
passphrase = self.password_encode(password)
185
with tempfile.NamedTemporaryFile(dir=self.tempdir
187
passfile.write(passphrase)
189
proc = subprocess.Popen(['gpg', '--symmetric',
193
stdin = subprocess.PIPE,
194
stdout = subprocess.PIPE,
195
stderr = subprocess.PIPE)
196
ciphertext, err = proc.communicate(input = data)
197
if proc.returncode != 0:
201
def decrypt(self, data, password):
202
passphrase = self.password_encode(password)
203
with tempfile.NamedTemporaryFile(dir = self.tempdir
205
passfile.write(passphrase)
207
proc = subprocess.Popen(['gpg', '--decrypt',
211
stdin = subprocess.PIPE,
212
stdout = subprocess.PIPE,
213
stderr = subprocess.PIPE)
214
decrypted_plaintext, err = proc.communicate(input
216
if proc.returncode != 0:
218
return decrypted_plaintext
109
221
class AvahiError(Exception):
311
434
last_approval_request: datetime.datetime(); (UTC) or None
312
435
last_checked_ok: datetime.datetime(); (UTC) or None
313
436
last_checker_status: integer between 0 and 255 reflecting exit
314
status of last checker. -1 reflect crashed
316
last_enabled: datetime.datetime(); (UTC)
437
status of last checker. -1 reflects crashed
438
checker, -2 means no checker completed yet.
439
last_enabled: datetime.datetime(); (UTC) or None
317
440
name: string; from the config file, used in log messages and
318
441
D-Bus identifiers
319
442
secret: bytestring; sent verbatim (over TLS) to client
320
443
timeout: datetime.timedelta(); How long from last_checked_ok
321
444
until this client is disabled
322
extended_timeout: extra long timeout when password has been sent
445
extended_timeout: extra long timeout when secret has been sent
323
446
runtime_expansions: Allowed attributes for runtime expansion.
324
447
expires: datetime.datetime(); time (UTC) when a client will be
325
448
disabled, or None
449
server_settings: The server_settings dict from main()
328
452
runtime_expansions = ("approval_delay", "approval_duration",
329
"created", "enabled", "fingerprint",
330
"host", "interval", "last_checked_ok",
453
"created", "enabled", "expires",
454
"fingerprint", "host", "interval",
455
"last_approval_request", "last_checked_ok",
331
456
"last_enabled", "name", "timeout")
457
client_defaults = { "timeout": "PT5M",
458
"extended_timeout": "PT15M",
460
"checker": "fping -q -- %%(host)s",
462
"approval_delay": "PT0S",
463
"approval_duration": "PT1S",
464
"approved_by_default": "True",
333
468
def timeout_milliseconds(self):
334
469
"Return the 'timeout' attribute in milliseconds"
335
return _timedelta_to_milliseconds(self.timeout)
470
return timedelta_to_milliseconds(self.timeout)
337
472
def extended_timeout_milliseconds(self):
338
473
"Return the 'extended_timeout' attribute in milliseconds"
339
return _timedelta_to_milliseconds(self.extended_timeout)
474
return timedelta_to_milliseconds(self.extended_timeout)
341
476
def interval_milliseconds(self):
342
477
"Return the 'interval' attribute in milliseconds"
343
return _timedelta_to_milliseconds(self.interval)
478
return timedelta_to_milliseconds(self.interval)
345
480
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'
481
return timedelta_to_milliseconds(self.approval_delay)
484
def config_parser(config):
485
"""Construct a new dict of client settings of this form:
486
{ client_name: {setting_name: value, ...}, ...}
487
with exceptions for any special settings as defined above.
488
NOTE: Must be a pure function. Must return the same result
489
value given the same arguments.
492
for client_name in config.sections():
493
section = dict(config.items(client_name))
494
client = settings[client_name] = {}
496
client["host"] = section["host"]
497
# Reformat values from string types to Python types
498
client["approved_by_default"] = config.getboolean(
499
client_name, "approved_by_default")
500
client["enabled"] = config.getboolean(client_name,
503
client["fingerprint"] = (section["fingerprint"].upper()
505
if "secret" in section:
506
client["secret"] = section["secret"].decode("base64")
507
elif "secfile" in section:
508
with open(os.path.expanduser(os.path.expandvars
509
(section["secfile"])),
511
client["secret"] = secfile.read()
513
raise TypeError("No secret or secfile for section {0}"
515
client["timeout"] = string_to_delta(section["timeout"])
516
client["extended_timeout"] = string_to_delta(
517
section["extended_timeout"])
518
client["interval"] = string_to_delta(section["interval"])
519
client["approval_delay"] = string_to_delta(
520
section["approval_delay"])
521
client["approval_duration"] = string_to_delta(
522
section["approval_duration"])
523
client["checker_command"] = section["checker"]
524
client["last_approval_request"] = None
525
client["last_checked_ok"] = None
526
client["last_checker_status"] = -2
530
def __init__(self, settings, name = None, server_settings=None):
532
if server_settings is None:
534
self.server_settings = server_settings
535
# adding all client settings
536
for setting, value in settings.iteritems():
537
setattr(self, setting, value)
540
if not hasattr(self, "last_enabled"):
541
self.last_enabled = datetime.datetime.utcnow()
542
if not hasattr(self, "expires"):
543
self.expires = (datetime.datetime.utcnow()
546
self.last_enabled = None
355
549
logger.debug("Creating client %r", self.name)
356
550
# Uppercase and remove spaces from fingerprint for later
357
551
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
361
553
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"])
554
self.created = settings.get("created",
555
datetime.datetime.utcnow())
557
# attributes specific for this server instance
383
558
self.checker = None
384
559
self.checker_initiator_tag = None
385
560
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
387
561
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
389
562
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
393
564
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
565
self.changedstate = (multiprocessing_manager
399
566
.Condition(multiprocessing_manager
401
self.client_structure = [attr for attr
402
in self.__dict__.iterkeys()
568
self.client_structure = [attr for attr in
569
self.__dict__.iterkeys()
403
570
if not attr.startswith("_")]
404
571
self.client_structure.append("client_structure")
407
573
for name, t in inspect.getmembers(type(self),
421
587
if getattr(self, "enabled", False):
422
588
# Already enabled
424
self.send_changedstate()
425
590
self.expires = datetime.datetime.utcnow() + self.timeout
426
591
self.enabled = True
427
592
self.last_enabled = datetime.datetime.utcnow()
428
593
self.init_checker()
594
self.send_changedstate()
430
596
def disable(self, quiet=True):
431
597
"""Disable this client."""
432
598
if not getattr(self, "enabled", False):
435
self.send_changedstate()
437
601
logger.info("Disabling client %s", self.name)
438
if getattr(self, "disable_initiator_tag", False):
602
if getattr(self, "disable_initiator_tag", None) is not None:
439
603
gobject.source_remove(self.disable_initiator_tag)
440
604
self.disable_initiator_tag = None
441
605
self.expires = None
442
if getattr(self, "checker_initiator_tag", False):
606
if getattr(self, "checker_initiator_tag", None) is not None:
443
607
gobject.source_remove(self.checker_initiator_tag)
444
608
self.checker_initiator_tag = None
445
609
self.stop_checker()
446
610
self.enabled = False
612
self.send_changedstate()
447
613
# Do not run this again if called by a gobject.timeout_add
450
616
def __del__(self):
453
619
def init_checker(self):
454
620
# Schedule a new checker to be started an 'interval' from now,
455
621
# and every interval from then on.
622
if self.checker_initiator_tag is not None:
623
gobject.source_remove(self.checker_initiator_tag)
456
624
self.checker_initiator_tag = (gobject.timeout_add
457
625
(self.interval_milliseconds(),
458
626
self.start_checker))
459
627
# Schedule a disable() when 'timeout' has passed
628
if self.disable_initiator_tag is not None:
629
gobject.source_remove(self.disable_initiator_tag)
460
630
self.disable_initiator_tag = (gobject.timeout_add
461
631
(self.timeout_milliseconds(),
463
633
# Also start a new checker *right now*.
464
634
self.start_checker()
467
636
def checker_callback(self, pid, condition, command):
468
637
"""The checker has completed, so take appropriate actions."""
469
638
self.checker_callback_tag = None
470
639
self.checker = None
471
640
if os.WIFEXITED(condition):
472
self.last_checker_status = os.WEXITSTATUS(condition)
641
self.last_checker_status = os.WEXITSTATUS(condition)
473
642
if self.last_checker_status == 0:
474
643
logger.info("Checker for %(name)s succeeded",
558
721
# in normal mode, that is already done by daemon(),
559
722
# and in debug mode we don't want to. (Stdin is
560
723
# always replaced by /dev/null.)
724
# The exception is when not debugging but nevertheless
725
# running in the foreground; use the previously
728
if (not self.server_settings["debug"]
729
and self.server_settings["foreground"]):
730
popen_args.update({"stdout": wnull,
561
732
self.checker = subprocess.Popen(command,
564
self.checker_callback_tag = (gobject.child_watch_add
566
self.checker_callback,
568
# The checker may have completed before the gobject
569
# watch was added. Check for this.
736
except OSError as error:
737
logger.error("Failed to start subprocess",
740
self.checker_callback_tag = (gobject.child_watch_add
742
self.checker_callback,
744
# The checker may have completed before the gobject
745
# watch was added. Check for this.
570
747
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
572
gobject.source_remove(self.checker_callback_tag)
573
self.checker_callback(pid, status, command)
574
748
except OSError as error:
575
logger.error("Failed to start subprocess: %s",
749
if error.errno == errno.ECHILD:
750
# This should never happen
751
logger.error("Child process vanished",
756
gobject.source_remove(self.checker_callback_tag)
757
self.checker_callback(pid, status, command)
577
758
# Re-run this periodically if run by gobject.timeout_add
587
768
logger.debug("Stopping checker for %(name)s", vars(self))
589
os.kill(self.checker.pid, signal.SIGTERM)
770
self.checker.terminate()
591
772
#if self.checker.poll() is None:
592
# os.kill(self.checker.pid, signal.SIGKILL)
773
# self.checker.kill()
593
774
except OSError as error:
594
775
if error.errno != errno.ESRCH: # No such process
596
777
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
780
def dbus_service_property(dbus_interface, signature="v",
650
781
access="readwrite", byte_arrays=False):
803
983
e.setAttribute("access", prop._dbus_access)
805
985
for if_tag in document.getElementsByTagName("interface"):
806
987
for tag in (make_tag(document, name, prop)
808
in self._get_all_dbus_properties()
989
in self._get_all_dbus_things("property")
809
990
if prop._dbus_interface
810
991
== if_tag.getAttribute("name")):
811
992
if_tag.appendChild(tag)
993
# Add annotation tags
994
for typ in ("method", "signal", "property"):
995
for tag in if_tag.getElementsByTagName(typ):
997
for name, prop in (self.
998
_get_all_dbus_things(typ)):
999
if (name == tag.getAttribute("name")
1000
and prop._dbus_interface
1001
== if_tag.getAttribute("name")):
1002
annots.update(getattr
1004
"_dbus_annotations",
1006
for name, value in annots.iteritems():
1007
ann_tag = document.createElement(
1009
ann_tag.setAttribute("name", name)
1010
ann_tag.setAttribute("value", value)
1011
tag.appendChild(ann_tag)
1012
# Add interface annotation tags
1013
for annotation, value in dict(
1014
itertools.chain.from_iterable(
1015
annotations().iteritems()
1016
for name, annotations in
1017
self._get_all_dbus_things("interface")
1018
if name == if_tag.getAttribute("name")
1020
ann_tag = document.createElement("annotation")
1021
ann_tag.setAttribute("name", annotation)
1022
ann_tag.setAttribute("value", value)
1023
if_tag.appendChild(ann_tag)
812
1024
# Add the names to the return values for the
813
1025
# "org.freedesktop.DBus.Properties" methods
814
1026
if (if_tag.getAttribute("name")
829
1041
except (AttributeError, xml.dom.DOMException,
830
1042
xml.parsers.expat.ExpatError) as error:
831
1043
logger.error("Failed to override Introspection method",
833
1045
return xmlstring
836
def datetime_to_dbus (dt, variant_level=0):
1048
def datetime_to_dbus(dt, variant_level=0):
837
1049
"""Convert a UTC datetime.datetime() to a D-Bus type."""
839
1051
return dbus.String("", variant_level = variant_level)
840
1052
return dbus.String(dt.isoformat(),
841
1053
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.
1056
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1057
"""A class decorator; applied to a subclass of
1058
dbus.service.Object, it will add alternate D-Bus attributes with
1059
interface names according to the "alt_interface_names" mapping.
1062
@alternate_dbus_interfaces({"org.example.Interface":
1063
"net.example.AlternateInterface"})
1064
class SampleDBusObject(dbus.service.Object):
1065
@dbus.service.method("org.example.Interface")
1066
def SampleDBusMethod():
1069
The above "SampleDBusMethod" on "SampleDBusObject" will be
1070
reachable via two interfaces: "org.example.Interface" and
1071
"net.example.AlternateInterface", the latter of which will have
1072
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1073
"true", unless "deprecate" is passed with a False value.
1075
This works for methods and signals, and also for D-Bus properties
1076
(from DBusObjectWithProperties) and interfaces (from the
1077
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):
1080
for orig_interface_name, alt_interface_name in (
1081
alt_interface_names.iteritems()):
1083
interface_names = set()
1084
# Go though all attributes of the class
1085
for attrname, attribute in inspect.getmembers(cls):
855
1086
# Ignore non-D-Bus attributes, and D-Bus attributes
856
1087
# with the wrong interface name
857
1088
if (not hasattr(attribute, "_dbus_interface")
858
1089
or not attribute._dbus_interface
859
.startswith("se.recompile.Mandos")):
1090
.startswith(orig_interface_name)):
861
1092
# Create an alternate D-Bus interface name based on
862
1093
# the current name
863
1094
alt_interface = (attribute._dbus_interface
864
.replace("se.recompile.Mandos",
865
"se.bsnet.fukt.Mandos"))
1095
.replace(orig_interface_name,
1096
alt_interface_name))
1097
interface_names.add(alt_interface)
866
1098
# Is this a D-Bus signal?
867
1099
if getattr(attribute, "_dbus_is_signal", False):
868
# Extract the original non-method function by
1100
# Extract the original non-method undecorated
1101
# function by black magic
870
1102
nonmethod_func = (dict(
871
1103
zip(attribute.func_code.co_freevars,
872
1104
attribute.__closure__))["func"]
935
1179
attribute.func_name,
936
1180
attribute.func_defaults,
937
1181
attribute.func_closure)))
938
return type.__new__(mcs, name, bases, attr)
1182
# Copy annotations, if any
1184
attr[attrname]._dbus_annotations = (
1185
dict(attribute._dbus_annotations))
1186
except AttributeError:
1188
# Is this a D-Bus interface?
1189
elif getattr(attribute, "_dbus_is_interface", False):
1190
# Create a new, but exactly alike, function
1191
# object. Decorate it to be a new D-Bus interface
1192
# with the alternate D-Bus interface name. Add it
1194
attr[attrname] = (dbus_interface_annotations
1197
(attribute.func_code,
1198
attribute.func_globals,
1199
attribute.func_name,
1200
attribute.func_defaults,
1201
attribute.func_closure)))
1203
# Deprecate all alternate interfaces
1204
iname="_AlternateDBusNames_interface_annotation{0}"
1205
for interface_name in interface_names:
1206
@dbus_interface_annotations(interface_name)
1208
return { "org.freedesktop.DBus.Deprecated":
1210
# Find an unused name
1211
for aname in (iname.format(i)
1212
for i in itertools.count()):
1213
if aname not in attr:
1217
# Replace the class with a new subclass of it with
1218
# methods, signals, etc. as created above.
1219
cls = type(b"{0}Alternate".format(cls.__name__),
1225
@alternate_dbus_interfaces({"se.recompile.Mandos":
1226
"se.bsnet.fukt.Mandos"})
940
1227
class ClientDBus(Client, DBusObjectWithProperties):
941
1228
"""A Client class using D-Bus
1008
1290
checker is not None)
1009
1291
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1010
1292
"LastCheckedOK")
1293
last_checker_status = notifychangeproperty(dbus.Int16,
1294
"LastCheckerStatus")
1011
1295
last_approval_request = notifychangeproperty(
1012
1296
datetime_to_dbus, "LastApprovalRequest")
1013
1297
approved_by_default = notifychangeproperty(dbus.Boolean,
1014
1298
"ApprovedByDefault")
1015
approval_delay = notifychangeproperty(dbus.UInt16,
1299
approval_delay = notifychangeproperty(dbus.UInt64,
1016
1300
"ApprovalDelay",
1018
_timedelta_to_milliseconds)
1302
timedelta_to_milliseconds)
1019
1303
approval_duration = notifychangeproperty(
1020
dbus.UInt16, "ApprovalDuration",
1021
type_func = _timedelta_to_milliseconds)
1304
dbus.UInt64, "ApprovalDuration",
1305
type_func = timedelta_to_milliseconds)
1022
1306
host = notifychangeproperty(dbus.String, "Host")
1023
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1307
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1025
_timedelta_to_milliseconds)
1309
timedelta_to_milliseconds)
1026
1310
extended_timeout = notifychangeproperty(
1027
dbus.UInt16, "ExtendedTimeout",
1028
type_func = _timedelta_to_milliseconds)
1029
interval = notifychangeproperty(dbus.UInt16,
1311
dbus.UInt64, "ExtendedTimeout",
1312
type_func = timedelta_to_milliseconds)
1313
interval = notifychangeproperty(dbus.UInt64,
1032
_timedelta_to_milliseconds)
1316
timedelta_to_milliseconds)
1033
1317
checker_command = notifychangeproperty(dbus.String, "Checker")
1035
1319
del notifychangeproperty
1635
1928
use_ipv6: Boolean; to use IPv6 or not
1637
1930
def __init__(self, server_address, RequestHandlerClass,
1638
interface=None, use_ipv6=True):
1931
interface=None, use_ipv6=True, socketfd=None):
1932
"""If socketfd is set, use that file descriptor instead of
1933
creating a new one with socket.socket().
1639
1935
self.interface = interface
1641
1937
self.address_family = socket.AF_INET6
1938
if socketfd is not None:
1939
# Save the file descriptor
1940
self.socketfd = socketfd
1941
# Save the original socket.socket() function
1942
self.socket_socket = socket.socket
1943
# To implement --socket, we monkey patch socket.socket.
1945
# (When socketserver.TCPServer is a new-style class, we
1946
# could make self.socket into a property instead of monkey
1947
# patching socket.socket.)
1949
# Create a one-time-only replacement for socket.socket()
1950
@functools.wraps(socket.socket)
1951
def socket_wrapper(*args, **kwargs):
1952
# Restore original function so subsequent calls are
1954
socket.socket = self.socket_socket
1955
del self.socket_socket
1956
# This time only, return a new socket object from the
1957
# saved file descriptor.
1958
return socket.fromfd(self.socketfd, *args, **kwargs)
1959
# Replace socket.socket() function with wrapper
1960
socket.socket = socket_wrapper
1961
# The socketserver.TCPServer.__init__ will call
1962
# socket.socket(), which might be our replacement,
1963
# socket_wrapper(), if socketfd was set.
1642
1964
socketserver.TCPServer.__init__(self, server_address,
1643
1965
RequestHandlerClass)
1644
1967
def server_bind(self):
1645
1968
"""This overrides the normal server_bind() function
1646
1969
to bind to an interface if one was specified, and also NOT to
2122
def rfc3339_duration_to_delta(duration):
2123
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2125
>>> rfc3339_duration_to_delta("P7D")
2126
datetime.timedelta(7)
2127
>>> rfc3339_duration_to_delta("PT60S")
2128
datetime.timedelta(0, 60)
2129
>>> rfc3339_duration_to_delta("PT60M")
2130
datetime.timedelta(0, 3600)
2131
>>> rfc3339_duration_to_delta("PT24H")
2132
datetime.timedelta(1)
2133
>>> rfc3339_duration_to_delta("P1W")
2134
datetime.timedelta(7)
2135
>>> rfc3339_duration_to_delta("PT5M30S")
2136
datetime.timedelta(0, 330)
2137
>>> rfc3339_duration_to_delta("P1DT3M20S")
2138
datetime.timedelta(1, 200)
2141
# Parsing an RFC 3339 duration with regular expressions is not
2142
# possible - there would have to be multiple places for the same
2143
# values, like seconds. The current code, while more esoteric, is
2144
# cleaner without depending on a parsing library. If Python had a
2145
# built-in library for parsing we would use it, but we'd like to
2146
# avoid excessive use of external libraries.
2148
# New type for defining tokens, syntax, and semantics all-in-one
2149
Token = collections.namedtuple("Token",
2150
("regexp", # To match token; if
2151
# "value" is not None,
2152
# must have a "group"
2154
"value", # datetime.timedelta or
2156
"followers")) # Tokens valid after
2158
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2159
# the "duration" ABNF definition in RFC 3339, Appendix A.
2160
token_end = Token(re.compile(r"$"), None, frozenset())
2161
token_second = Token(re.compile(r"(\d+)S"),
2162
datetime.timedelta(seconds=1),
2163
frozenset((token_end,)))
2164
token_minute = Token(re.compile(r"(\d+)M"),
2165
datetime.timedelta(minutes=1),
2166
frozenset((token_second, token_end)))
2167
token_hour = Token(re.compile(r"(\d+)H"),
2168
datetime.timedelta(hours=1),
2169
frozenset((token_minute, token_end)))
2170
token_time = Token(re.compile(r"T"),
2172
frozenset((token_hour, token_minute,
2174
token_day = Token(re.compile(r"(\d+)D"),
2175
datetime.timedelta(days=1),
2176
frozenset((token_time, token_end)))
2177
token_month = Token(re.compile(r"(\d+)M"),
2178
datetime.timedelta(weeks=4),
2179
frozenset((token_day, token_end)))
2180
token_year = Token(re.compile(r"(\d+)Y"),
2181
datetime.timedelta(weeks=52),
2182
frozenset((token_month, token_end)))
2183
token_week = Token(re.compile(r"(\d+)W"),
2184
datetime.timedelta(weeks=1),
2185
frozenset((token_end,)))
2186
token_duration = Token(re.compile(r"P"), None,
2187
frozenset((token_year, token_month,
2188
token_day, token_time,
2190
# Define starting values
2191
value = datetime.timedelta() # Value so far
2193
followers = frozenset(token_duration,) # Following valid tokens
2194
s = duration # String left to parse
2195
# Loop until end token is found
2196
while found_token is not token_end:
2197
# Search for any currently valid tokens
2198
for token in followers:
2199
match = token.regexp.match(s)
2200
if match is not None:
2202
if token.value is not None:
2203
# Value found, parse digits
2204
factor = int(match.group(1), 10)
2205
# Add to value so far
2206
value += factor * token.value
2207
# Strip token from string
2208
s = token.regexp.sub("", s, 1)
2211
# Set valid next tokens
2212
followers = found_token.followers
2215
# No currently valid tokens were found
2216
raise ValueError("Invalid RFC 3339 duration")
1811
2221
def string_to_delta(interval):
1812
2222
"""Parse a string and return a datetime.timedelta
1964
2368
# Convert the SafeConfigParser object to a dict
1965
2369
server_settings = server_config.defaults()
1966
2370
# Use the appropriate methods on the non-string config options
1967
for option in ("debug", "use_dbus", "use_ipv6"):
2371
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
1968
2372
server_settings[option] = server_config.getboolean("DEFAULT",
1970
2374
if server_settings["port"]:
1971
2375
server_settings["port"] = server_config.getint("DEFAULT",
2377
if server_settings["socket"]:
2378
server_settings["socket"] = server_config.getint("DEFAULT",
2380
# Later, stdin will, and stdout and stderr might, be dup'ed
2381
# over with an opened os.devnull. But we don't want this to
2382
# happen with a supplied network socket.
2383
if 0 <= server_settings["socket"] <= 2:
2384
server_settings["socket"] = os.dup(server_settings
1973
2386
del server_config
1975
2388
# Override the settings from the config file with command line
1976
2389
# options, if set.
1977
2390
for option in ("interface", "address", "port", "debug",
1978
2391
"priority", "servicename", "configdir",
1979
"use_dbus", "use_ipv6", "debuglevel", "restore"):
2392
"use_dbus", "use_ipv6", "debuglevel", "restore",
2393
"statedir", "socket", "foreground"):
1980
2394
value = getattr(options, option)
1981
2395
if value is not None:
1982
2396
server_settings[option] = value
2025
2452
use_ipv6=use_ipv6,
2026
2453
gnutls_priority=
2027
2454
server_settings["priority"],
2030
pidfilename = "/var/run/mandos.pid"
2456
socketfd=(server_settings["socket"]
2459
pidfilename = "/run/mandos.pid"
2460
if not os.path.isdir("/run/."):
2461
pidfilename = "/var/run/mandos.pid"
2032
2464
pidfile = open(pidfilename, "w")
2034
logger.error("Could not open file %r", pidfilename)
2465
except IOError as e:
2466
logger.error("Could not open file %r", pidfilename,
2037
uid = pwd.getpwnam("_mandos").pw_uid
2038
gid = pwd.getpwnam("_mandos").pw_gid
2469
for name in ("_mandos", "mandos", "nobody"):
2041
uid = pwd.getpwnam("mandos").pw_uid
2042
gid = pwd.getpwnam("mandos").pw_gid
2471
uid = pwd.getpwnam(name).pw_uid
2472
gid = pwd.getpwnam(name).pw_gid
2043
2474
except KeyError:
2045
uid = pwd.getpwnam("nobody").pw_uid
2046
gid = pwd.getpwnam("nobody").pw_gid
2053
2482
except OSError as error:
2054
if error[0] != errno.EPERM:
2483
if error.errno != errno.EPERM:
2057
if not debug and not debuglevel:
2058
logger.setLevel(logging.WARNING)
2060
level = getattr(logging, debuglevel.upper())
2061
logger.setLevel(level)
2064
logger.setLevel(logging.DEBUG)
2065
2487
# Enable all possible GnuTLS debugging
2067
2489
# "Use a log level over 10 to enable all debugging options."
2122
2545
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())
2547
client_class = functools.partial(ClientDBus, bus = bus)
2549
client_settings = Client.config_parser(client_config)
2147
2550
old_client_settings = {}
2150
# Get client data and settings from last running state.
2553
# This is used to redirect stdout and stderr for checker processes
2555
wnull = open(os.devnull, "w") # A writable /dev/null
2556
# Only used if server is running in foreground but not in debug
2558
if debug or not foreground:
2561
# Get client data and settings from last running state.
2151
2562
if server_settings["restore"]:
2153
2564
with open(stored_state_path, "rb") as stored_state:
2154
clients_data, old_client_settings = (
2155
pickle.load(stored_state))
2565
clients_data, old_client_settings = (pickle.load
2156
2567
os.remove(stored_state_path)
2157
2568
except IOError as e:
2158
logger.warning("Could not load persistant state: {0}"
2160
if e.errno != errno.ENOENT:
2569
if e.errno == errno.ENOENT:
2570
logger.warning("Could not load persistent state: {0}"
2571
.format(os.strerror(e.errno)))
2573
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():
2576
except EOFError as e:
2577
logger.warning("Could not load persistent state: "
2578
"EOFError:", exc_info=e)
2580
with PGPEngine() as pgp:
2581
for client_name, client in clients_data.iteritems():
2582
# Skip removed clients
2583
if client_name not in client_settings:
2586
# Decide which value to use after restoring saved state.
2587
# We have three different values: Old config file,
2588
# new config file, and saved state.
2589
# New config value takes precedence if it differs from old
2590
# config value, otherwise use saved state.
2591
for name, value in client_settings[client_name].items():
2593
# For each value in new config, check if it
2594
# differs from the old config value (Except for
2595
# the "secret" attribute)
2596
if (name != "secret" and
2597
value != old_client_settings[client_name]
2599
client[name] = value
2603
# Clients who has passed its expire date can still be
2604
# enabled if its last checker was successful. Clients
2605
# whose checker succeeded before we stored its state is
2606
# assumed to have successfully run all checkers during
2608
if client["enabled"]:
2609
if datetime.datetime.utcnow() >= client["expires"]:
2610
if not client["last_checked_ok"]:
2612
"disabling client {0} - Client never "
2613
"performed a successful checker"
2614
.format(client_name))
2615
client["enabled"] = False
2616
elif client["last_checker_status"] != 0:
2618
"disabling client {0} - Client "
2619
"last checker failed with error code {1}"
2620
.format(client_name,
2621
client["last_checker_status"]))
2622
client["enabled"] = False
2624
client["expires"] = (datetime.datetime
2626
+ client["timeout"])
2627
logger.debug("Last checker succeeded,"
2628
" keeping {0} enabled"
2629
.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
2631
client["secret"] = (
2632
pgp.decrypt(client["encrypted_secret"],
2633
client_settings[client_name]
2636
# If decryption fails, we use secret from new settings
2637
logger.debug("Failed to decrypt {0} old secret"
2638
.format(client_name))
2639
client["secret"] = (
2640
client_settings[client_name]["secret"])
2642
# Add/remove clients based on new changes made to config
2643
for client_name in (set(old_client_settings)
2644
- set(client_settings)):
2645
del clients_data[client_name]
2646
for client_name in (set(client_settings)
2647
- set(old_client_settings)):
2648
clients_data[client_name] = client_settings[client_name]
2650
# Create all client objects
2651
for client_name, client in clients_data.iteritems():
2652
tcp_server.clients[client_name] = client_class(
2653
name = client_name, settings = client,
2654
server_settings = server_settings)
2225
2656
if not tcp_server.clients:
2226
2657
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
2660
if pidfile is not None:
2664
pidfile.write(str(pid) + "\n".encode("utf-8"))
2666
logger.error("Could not write to file %r with PID %d",
2240
2669
del pidfilename
2242
signal.signal(signal.SIGINT, signal.SIG_IGN)
2244
2671
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2245
2672
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2248
class MandosDBusService(dbus.service.Object):
2675
@alternate_dbus_interfaces({"se.recompile.Mandos":
2676
"se.bsnet.fukt.Mandos"})
2677
class MandosDBusService(DBusObjectWithProperties):
2249
2678
"""A D-Bus proxy object"""
2250
2679
def __init__(self):
2251
2680
dbus.service.Object.__init__(self, bus, "/")
2252
2681
_interface = "se.recompile.Mandos"
2683
@dbus_interface_annotations(_interface)
2685
return { "org.freedesktop.DBus.Property"
2686
".EmitsChangedSignal":
2254
2689
@dbus.service.signal(_interface, signature="o")
2255
2690
def ClientAdded(self, objpath):
2301
class MandosDBusServiceTransitional(MandosDBusService):
2302
__metaclass__ = AlternateDBusNamesMetaclass
2303
mandos_dbus_service = MandosDBusServiceTransitional()
2736
mandos_dbus_service = MandosDBusService()
2306
2739
"Cleanup function; run on exit"
2307
2740
service.cleanup()
2309
2742
multiprocessing.active_children()
2310
2744
if not (tcp_server.clients or client_settings):
2313
2747
# Store client before exiting. Secrets are encrypted with key
2314
2748
# based on what config file has. If config file is
2315
2749
# 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"]
2751
with PGPEngine() as pgp:
2752
for client in tcp_server.clients.itervalues():
2753
key = client_settings[client.name]["secret"]
2754
client.encrypted_secret = pgp.encrypt(client.secret,
2758
# A list of attributes that can not be pickled
2760
exclude = set(("bus", "changedstate", "secret",
2761
"checker", "server_settings"))
2762
for name, typ in (inspect.getmembers
2763
(dbus.service.Object)):
2766
client_dict["encrypted_secret"] = (client
2768
for attr in client.client_structure:
2769
if attr not in exclude:
2770
client_dict[attr] = getattr(client, attr)
2772
clients[client.name] = client_dict
2773
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:
2776
with (tempfile.NamedTemporaryFile
2777
(mode='wb', suffix=".pickle", prefix='clients-',
2778
dir=os.path.dirname(stored_state_path),
2779
delete=False)) as stored_state:
2342
2780
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:
2781
tempname=stored_state.name
2782
os.rename(tempname, stored_state_path)
2783
except (IOError, OSError) as e:
2789
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2790
logger.warning("Could not save persistent state: {0}"
2791
.format(os.strerror(e.errno)))
2793
logger.warning("Could not save persistent state:",
2349
2797
# Delete all clients, and settings from config
2350
2798
while tcp_server.clients:
2351
2799
name, client = tcp_server.clients.popitem()