89
81
except ImportError:
90
82
SO_BINDTODEVICE = None
93
stored_state_file = "clients.pickle"
95
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
96
89
syslogger = (logging.handlers.SysLogHandler
97
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
98
91
address = str("/dev/log")))
101
if_nametoindex = (ctypes.cdll.LoadLibrary
102
(ctypes.util.find_library("c"))
104
except (OSError, AttributeError):
105
def if_nametoindex(interface):
106
"Get an interface index the hard way, i.e. using fcntl()"
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
108
with contextlib.closing(socket.socket()) as s:
109
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
struct.pack(str("16s16x"),
112
interface_index = struct.unpack(str("I"),
114
return interface_index
117
def initlogger(debug, level=logging.WARNING):
118
"""init logger and add loglevel"""
120
syslogger.setFormatter(logging.Formatter
121
('Mandos [%(process)d]: %(levelname)s:'
123
logger.addHandler(syslogger)
126
console = logging.StreamHandler()
127
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
131
logger.addHandler(console)
132
logger.setLevel(level)
135
class PGPError(Exception):
136
"""Exception if encryption/decryption fails"""
140
class PGPEngine(object):
141
"""A simple class for OpenPGP symmetric encryption & decryption"""
143
self.gnupg = GnuPGInterface.GnuPG()
144
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
145
self.gnupg = GnuPGInterface.GnuPG()
146
self.gnupg.options.meta_interactive = False
147
self.gnupg.options.homedir = self.tempdir
148
self.gnupg.options.extra_args.extend(['--force-mdc',
155
def __exit__(self, exc_type, exc_value, traceback):
163
if self.tempdir is not None:
164
# Delete contents of tempdir
165
for root, dirs, files in os.walk(self.tempdir,
167
for filename in files:
168
os.remove(os.path.join(root, filename))
170
os.rmdir(os.path.join(root, dirname))
172
os.rmdir(self.tempdir)
175
def password_encode(self, password):
176
# Passphrase can not be empty and can not contain newlines or
177
# NUL bytes. So we prefix it and hex encode it.
178
return b"mandos" + binascii.hexlify(password)
180
def encrypt(self, data, password):
181
self.gnupg.passphrase = self.password_encode(password)
182
with open(os.devnull, "w") as devnull:
184
proc = self.gnupg.run(['--symmetric'],
185
create_fhs=['stdin', 'stdout'],
186
attach_fhs={'stderr': devnull})
187
with contextlib.closing(proc.handles['stdin']) as f:
189
with contextlib.closing(proc.handles['stdout']) as f:
190
ciphertext = f.read()
194
self.gnupg.passphrase = None
197
def decrypt(self, data, password):
198
self.gnupg.passphrase = self.password_encode(password)
199
with open(os.devnull, "w") as devnull:
201
proc = self.gnupg.run(['--decrypt'],
202
create_fhs=['stdin', 'stdout'],
203
attach_fhs={'stderr': devnull})
204
with contextlib.closing(proc.handles['stdin']) as f:
206
with contextlib.closing(proc.handles['stdout']) as f:
207
decrypted_plaintext = f.read()
211
self.gnupg.passphrase = None
212
return decrypted_plaintext
92
syslogger.setFormatter(logging.Formatter
93
('Mandos [%(process)d]: %(levelname)s:'
95
logger.addHandler(syslogger)
97
console = logging.StreamHandler()
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
101
logger.addHandler(console)
215
103
class AvahiError(Exception):
216
104
def __init__(self, value, *args, **kwargs):
427
297
interval: datetime.timedelta(); How often to start a new checker
428
298
last_approval_request: datetime.datetime(); (UTC) or None
429
299
last_checked_ok: datetime.datetime(); (UTC) or None
430
last_checker_status: integer between 0 and 255 reflecting exit
431
status of last checker. -1 reflects crashed
432
checker, -2 means no checker completed yet.
433
last_enabled: datetime.datetime(); (UTC) or None
300
last_enabled: datetime.datetime(); (UTC)
434
301
name: string; from the config file, used in log messages and
435
302
D-Bus identifiers
436
303
secret: bytestring; sent verbatim (over TLS) to client
437
304
timeout: datetime.timedelta(); How long from last_checked_ok
438
305
until this client is disabled
439
extended_timeout: extra long timeout when secret has been sent
306
extended_timeout: extra long timeout when password has been sent
440
307
runtime_expansions: Allowed attributes for runtime expansion.
441
308
expires: datetime.datetime(); time (UTC) when a client will be
442
309
disabled, or None
445
312
runtime_expansions = ("approval_delay", "approval_duration",
446
"created", "enabled", "expires",
447
"fingerprint", "host", "interval",
448
"last_approval_request", "last_checked_ok",
313
"created", "enabled", "fingerprint",
314
"host", "interval", "last_checked_ok",
449
315
"last_enabled", "name", "timeout")
450
client_defaults = { "timeout": "PT5M",
451
"extended_timeout": "PT15M",
453
"checker": "fping -q -- %%(host)s",
455
"approval_delay": "PT0S",
456
"approval_duration": "PT1S",
457
"approved_by_default": "True",
461
317
def timeout_milliseconds(self):
462
318
"Return the 'timeout' attribute in milliseconds"
463
return timedelta_to_milliseconds(self.timeout)
319
return _timedelta_to_milliseconds(self.timeout)
465
321
def extended_timeout_milliseconds(self):
466
322
"Return the 'extended_timeout' attribute in milliseconds"
467
return timedelta_to_milliseconds(self.extended_timeout)
323
return _timedelta_to_milliseconds(self.extended_timeout)
469
325
def interval_milliseconds(self):
470
326
"Return the 'interval' attribute in milliseconds"
471
return timedelta_to_milliseconds(self.interval)
327
return _timedelta_to_milliseconds(self.interval)
473
329
def approval_delay_milliseconds(self):
474
return timedelta_to_milliseconds(self.approval_delay)
477
def config_parser(config):
478
"""Construct a new dict of client settings of this form:
479
{ client_name: {setting_name: value, ...}, ...}
480
with exceptions for any special settings as defined above.
481
NOTE: Must be a pure function. Must return the same result
482
value given the same arguments.
485
for client_name in config.sections():
486
section = dict(config.items(client_name))
487
client = settings[client_name] = {}
489
client["host"] = section["host"]
490
# Reformat values from string types to Python types
491
client["approved_by_default"] = config.getboolean(
492
client_name, "approved_by_default")
493
client["enabled"] = config.getboolean(client_name,
496
client["fingerprint"] = (section["fingerprint"].upper()
498
if "secret" in section:
499
client["secret"] = section["secret"].decode("base64")
500
elif "secfile" in section:
501
with open(os.path.expanduser(os.path.expandvars
502
(section["secfile"])),
504
client["secret"] = secfile.read()
506
raise TypeError("No secret or secfile for section {0}"
508
client["timeout"] = string_to_delta(section["timeout"])
509
client["extended_timeout"] = string_to_delta(
510
section["extended_timeout"])
511
client["interval"] = string_to_delta(section["interval"])
512
client["approval_delay"] = string_to_delta(
513
section["approval_delay"])
514
client["approval_duration"] = string_to_delta(
515
section["approval_duration"])
516
client["checker_command"] = section["checker"]
517
client["last_approval_request"] = None
518
client["last_checked_ok"] = None
519
client["last_checker_status"] = -2
523
def __init__(self, settings, name = None):
330
return _timedelta_to_milliseconds(self.approval_delay)
332
def __init__(self, name = None, disable_hook=None, config=None):
333
"""Note: the 'checker' key in 'config' sets the
334
'checker_command' attribute and *not* the 'checker'
525
# adding all client settings
526
for setting, value in settings.iteritems():
527
setattr(self, setting, value)
530
if not hasattr(self, "last_enabled"):
531
self.last_enabled = datetime.datetime.utcnow()
532
if not hasattr(self, "expires"):
533
self.expires = (datetime.datetime.utcnow()
536
self.last_enabled = None
539
339
logger.debug("Creating client %r", self.name)
540
340
# Uppercase and remove spaces from fingerprint for later
541
341
# comparison purposes with return value from the fingerprint()
343
self.fingerprint = (config["fingerprint"].upper()
543
345
logger.debug(" Fingerprint: %s", self.fingerprint)
544
self.created = settings.get("created",
545
datetime.datetime.utcnow())
547
# attributes specific for this server instance
346
if "secret" in config:
347
self.secret = config["secret"].decode("base64")
348
elif "secfile" in config:
349
with open(os.path.expanduser(os.path.expandvars
350
(config["secfile"])),
352
self.secret = secfile.read()
354
raise TypeError("No secret or secfile for client %s"
356
self.host = config.get("host", "")
357
self.created = datetime.datetime.utcnow()
359
self.last_approval_request = None
360
self.last_enabled = None
361
self.last_checked_ok = None
362
self.timeout = string_to_delta(config["timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
364
self.interval = string_to_delta(config["interval"])
365
self.disable_hook = disable_hook
548
366
self.checker = None
549
367
self.checker_initiator_tag = None
550
368
self.disable_initiator_tag = None
551
370
self.checker_callback_tag = None
371
self.checker_command = config["checker"]
552
372
self.current_checker_command = None
373
self.last_connect = None
374
self._approved = None
375
self.approved_by_default = config.get("approved_by_default",
554
377
self.approvals_pending = 0
555
self.changedstate = (multiprocessing_manager
556
.Condition(multiprocessing_manager
558
self.client_structure = [attr for attr in
559
self.__dict__.iterkeys()
560
if not attr.startswith("_")]
561
self.client_structure.append("client_structure")
563
for name, t in inspect.getmembers(type(self),
567
if not name.startswith("_"):
568
self.client_structure.append(name)
378
self.approval_delay = string_to_delta(
379
config["approval_delay"])
380
self.approval_duration = string_to_delta(
381
config["approval_duration"])
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
570
# Send notice to process children that client state has changed
571
384
def send_changedstate(self):
572
with self.changedstate:
573
self.changedstate.notify_all()
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
575
389
def enable(self):
576
390
"""Start this client's checker and timeout hooks"""
577
391
if getattr(self, "enabled", False):
578
392
# Already enabled
394
self.send_changedstate()
395
# Schedule a new checker to be started an 'interval' from now,
396
# and every interval from then on.
397
self.checker_initiator_tag = (gobject.timeout_add
398
(self.interval_milliseconds(),
400
# Schedule a disable() when 'timeout' has passed
580
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
self.disable_initiator_tag = (gobject.timeout_add
403
(self.timeout_milliseconds(),
581
405
self.enabled = True
582
406
self.last_enabled = datetime.datetime.utcnow()
584
self.send_changedstate()
407
# Also start a new checker *right now*.
586
410
def disable(self, quiet=True):
587
411
"""Disable this client."""
588
412
if not getattr(self, "enabled", False):
415
self.send_changedstate()
591
417
logger.info("Disabling client %s", self.name)
592
if getattr(self, "disable_initiator_tag", None) is not None:
418
if getattr(self, "disable_initiator_tag", False):
593
419
gobject.source_remove(self.disable_initiator_tag)
594
420
self.disable_initiator_tag = None
595
421
self.expires = None
596
if getattr(self, "checker_initiator_tag", None) is not None:
422
if getattr(self, "checker_initiator_tag", False):
597
423
gobject.source_remove(self.checker_initiator_tag)
598
424
self.checker_initiator_tag = None
599
425
self.stop_checker()
426
if self.disable_hook:
427
self.disable_hook(self)
600
428
self.enabled = False
602
self.send_changedstate()
603
429
# Do not run this again if called by a gobject.timeout_add
606
432
def __del__(self):
433
self.disable_hook = None
609
def init_checker(self):
610
# Schedule a new checker to be started an 'interval' from now,
611
# and every interval from then on.
612
if self.checker_initiator_tag is not None:
613
gobject.source_remove(self.checker_initiator_tag)
614
self.checker_initiator_tag = (gobject.timeout_add
615
(self.interval_milliseconds(),
617
# Schedule a disable() when 'timeout' has passed
618
if self.disable_initiator_tag is not None:
619
gobject.source_remove(self.disable_initiator_tag)
620
self.disable_initiator_tag = (gobject.timeout_add
621
(self.timeout_milliseconds(),
623
# Also start a new checker *right now*.
626
436
def checker_callback(self, pid, condition, command):
627
437
"""The checker has completed, so take appropriate actions."""
628
438
self.checker_callback_tag = None
629
439
self.checker = None
630
440
if os.WIFEXITED(condition):
631
self.last_checker_status = os.WEXITSTATUS(condition)
632
if self.last_checker_status == 0:
441
exitstatus = os.WEXITSTATUS(condition)
633
443
logger.info("Checker for %(name)s succeeded",
635
445
self.checked_ok()
838
613
class DBusObjectWithProperties(dbus.service.Object):
839
614
"""A D-Bus object with properties.
841
616
Classes inheriting from this can use the dbus_service_property
842
617
decorator to expose methods as D-Bus properties. It exposes the
843
618
standard Get(), Set(), and GetAll() methods on the D-Bus.
847
def _is_dbus_thing(thing):
848
"""Returns a function testing if an attribute is a D-Bus thing
850
If called like _is_dbus_thing("method") it returns a function
851
suitable for use as predicate to inspect.getmembers().
853
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
622
def _is_dbus_property(obj):
623
return getattr(obj, "_dbus_is_property", False)
856
def _get_all_dbus_things(self, thing):
625
def _get_all_dbus_properties(self):
857
626
"""Returns a generator of (name, attribute) pairs
859
return ((getattr(athing.__get__(self), "_dbus_name",
861
athing.__get__(self))
862
for cls in self.__class__.__mro__
864
inspect.getmembers(cls,
865
self._is_dbus_thing(thing)))
628
return ((prop._dbus_name, prop)
630
inspect.getmembers(self, self._is_dbus_property))
867
632
def _get_dbus_property(self, interface_name, property_name):
868
633
"""Returns a bound method if one exists which is a D-Bus
869
634
property with the specified name and interface.
871
for cls in self.__class__.__mro__:
872
for name, value in (inspect.getmembers
874
self._is_dbus_thing("property"))):
875
if (value._dbus_name == property_name
876
and value._dbus_interface == interface_name):
877
return value.__get__(self)
636
for name in (property_name,
637
property_name + "_dbus_property"):
638
prop = getattr(self, name, None)
640
or not self._is_dbus_property(prop)
641
or prop._dbus_name != property_name
642
or (interface_name and prop._dbus_interface
643
and interface_name != prop._dbus_interface)):
879
646
# No such property
880
647
raise DBusPropertyNotFound(self.dbus_object_path + ":"
881
648
+ interface_name + "."
1013
746
except (AttributeError, xml.dom.DOMException,
1014
747
xml.parsers.expat.ExpatError) as error:
1015
748
logger.error("Failed to override Introspection method",
1017
750
return xmlstring
1020
def datetime_to_dbus(dt, variant_level=0):
753
def datetime_to_dbus (dt, variant_level=0):
1021
754
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1023
756
return dbus.String("", variant_level = variant_level)
1024
757
return dbus.String(dt.isoformat(),
1025
758
variant_level=variant_level)
1028
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1029
"""A class decorator; applied to a subclass of
1030
dbus.service.Object, it will add alternate D-Bus attributes with
1031
interface names according to the "alt_interface_names" mapping.
1034
@alternate_dbus_interfaces({"org.example.Interface":
1035
"net.example.AlternateInterface"})
1036
class SampleDBusObject(dbus.service.Object):
1037
@dbus.service.method("org.example.Interface")
1038
def SampleDBusMethod():
1041
The above "SampleDBusMethod" on "SampleDBusObject" will be
1042
reachable via two interfaces: "org.example.Interface" and
1043
"net.example.AlternateInterface", the latter of which will have
1044
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1045
"true", unless "deprecate" is passed with a False value.
1047
This works for methods and signals, and also for D-Bus properties
1048
(from DBusObjectWithProperties) and interfaces (from the
1049
dbus_interface_annotations decorator).
1052
for orig_interface_name, alt_interface_name in (
1053
alt_interface_names.iteritems()):
1055
interface_names = set()
1056
# Go though all attributes of the class
1057
for attrname, attribute in inspect.getmembers(cls):
1058
# Ignore non-D-Bus attributes, and D-Bus attributes
1059
# with the wrong interface name
1060
if (not hasattr(attribute, "_dbus_interface")
1061
or not attribute._dbus_interface
1062
.startswith(orig_interface_name)):
1064
# Create an alternate D-Bus interface name based on
1066
alt_interface = (attribute._dbus_interface
1067
.replace(orig_interface_name,
1068
alt_interface_name))
1069
interface_names.add(alt_interface)
1070
# Is this a D-Bus signal?
1071
if getattr(attribute, "_dbus_is_signal", False):
1072
# Extract the original non-method function by
1074
nonmethod_func = (dict(
1075
zip(attribute.func_code.co_freevars,
1076
attribute.__closure__))["func"]
1078
# Create a new, but exactly alike, function
1079
# object, and decorate it to be a new D-Bus signal
1080
# with the alternate D-Bus interface name
1081
new_function = (dbus.service.signal
1083
attribute._dbus_signature)
1084
(types.FunctionType(
1085
nonmethod_func.func_code,
1086
nonmethod_func.func_globals,
1087
nonmethod_func.func_name,
1088
nonmethod_func.func_defaults,
1089
nonmethod_func.func_closure)))
1090
# Copy annotations, if any
1092
new_function._dbus_annotations = (
1093
dict(attribute._dbus_annotations))
1094
except AttributeError:
1096
# Define a creator of a function to call both the
1097
# original and alternate functions, so both the
1098
# original and alternate signals gets sent when
1099
# the function is called
1100
def fixscope(func1, func2):
1101
"""This function is a scope container to pass
1102
func1 and func2 to the "call_both" function
1103
outside of its arguments"""
1104
def call_both(*args, **kwargs):
1105
"""This function will emit two D-Bus
1106
signals by calling func1 and func2"""
1107
func1(*args, **kwargs)
1108
func2(*args, **kwargs)
1110
# Create the "call_both" function and add it to
1112
attr[attrname] = fixscope(attribute, new_function)
1113
# Is this a D-Bus method?
1114
elif getattr(attribute, "_dbus_is_method", False):
1115
# Create a new, but exactly alike, function
1116
# object. Decorate it to be a new D-Bus method
1117
# with the alternate D-Bus interface name. Add it
1119
attr[attrname] = (dbus.service.method
1121
attribute._dbus_in_signature,
1122
attribute._dbus_out_signature)
1124
(attribute.func_code,
1125
attribute.func_globals,
1126
attribute.func_name,
1127
attribute.func_defaults,
1128
attribute.func_closure)))
1129
# Copy annotations, if any
1131
attr[attrname]._dbus_annotations = (
1132
dict(attribute._dbus_annotations))
1133
except AttributeError:
1135
# Is this a D-Bus property?
1136
elif getattr(attribute, "_dbus_is_property", False):
1137
# Create a new, but exactly alike, function
1138
# object, and decorate it to be a new D-Bus
1139
# property with the alternate D-Bus interface
1140
# name. Add it to the class.
1141
attr[attrname] = (dbus_service_property
1143
attribute._dbus_signature,
1144
attribute._dbus_access,
1146
._dbus_get_args_options
1149
(attribute.func_code,
1150
attribute.func_globals,
1151
attribute.func_name,
1152
attribute.func_defaults,
1153
attribute.func_closure)))
1154
# Copy annotations, if any
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1158
except AttributeError:
1160
# Is this a D-Bus interface?
1161
elif getattr(attribute, "_dbus_is_interface", False):
1162
# Create a new, but exactly alike, function
1163
# object. Decorate it to be a new D-Bus interface
1164
# with the alternate D-Bus interface name. Add it
1166
attr[attrname] = (dbus_interface_annotations
1169
(attribute.func_code,
1170
attribute.func_globals,
1171
attribute.func_name,
1172
attribute.func_defaults,
1173
attribute.func_closure)))
1175
# Deprecate all alternate interfaces
1176
iname="_AlternateDBusNames_interface_annotation{0}"
1177
for interface_name in interface_names:
1178
@dbus_interface_annotations(interface_name)
1180
return { "org.freedesktop.DBus.Deprecated":
1182
# Find an unused name
1183
for aname in (iname.format(i)
1184
for i in itertools.count()):
1185
if aname not in attr:
1189
# Replace the class with a new subclass of it with
1190
# methods, signals, etc. as created above.
1191
cls = type(b"{0}Alternate".format(cls.__name__),
1197
@alternate_dbus_interfaces({"se.recompile.Mandos":
1198
"se.bsnet.fukt.Mandos"})
1199
760
class ClientDBus(Client, DBusObjectWithProperties):
1200
761
"""A Client class using D-Bus
1258
818
last_enabled = notifychangeproperty(datetime_to_dbus,
1260
820
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1261
type_func = lambda checker:
1262
checker is not None)
821
type_func = lambda checker: checker is not None)
1263
822
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1264
823
"LastCheckedOK")
1265
last_checker_status = notifychangeproperty(dbus.Int16,
1266
"LastCheckerStatus")
1267
last_approval_request = notifychangeproperty(
1268
datetime_to_dbus, "LastApprovalRequest")
824
last_approval_request = notifychangeproperty(datetime_to_dbus,
825
"LastApprovalRequest")
1269
826
approved_by_default = notifychangeproperty(dbus.Boolean,
1270
827
"ApprovedByDefault")
1271
approval_delay = notifychangeproperty(dbus.UInt64,
1274
timedelta_to_milliseconds)
1275
approval_duration = notifychangeproperty(
1276
dbus.UInt64, "ApprovalDuration",
1277
type_func = timedelta_to_milliseconds)
828
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
829
type_func = _timedelta_to_milliseconds)
830
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
831
type_func = _timedelta_to_milliseconds)
1278
832
host = notifychangeproperty(dbus.String, "Host")
1279
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1281
timedelta_to_milliseconds)
1282
extended_timeout = notifychangeproperty(
1283
dbus.UInt64, "ExtendedTimeout",
1284
type_func = timedelta_to_milliseconds)
1285
interval = notifychangeproperty(dbus.UInt64,
1288
timedelta_to_milliseconds)
833
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
834
type_func = _timedelta_to_milliseconds)
835
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
836
type_func = _timedelta_to_milliseconds)
837
interval = notifychangeproperty(dbus.UInt16, "Interval",
838
type_func = _timedelta_to_milliseconds)
1289
839
checker_command = notifychangeproperty(dbus.String, "Checker")
1291
841
del notifychangeproperty
1997
1499
def __init__(self, server_address, RequestHandlerClass,
1998
1500
interface=None, use_ipv6=True, clients=None,
1999
gnutls_priority=None, use_dbus=True, socketfd=None):
1501
gnutls_priority=None, use_dbus=True):
2000
1502
self.enabled = False
2001
1503
self.clients = clients
2002
1504
if self.clients is None:
1505
self.clients = set()
2004
1506
self.use_dbus = use_dbus
2005
1507
self.gnutls_priority = gnutls_priority
2006
1508
IPv6_TCPServer.__init__(self, server_address,
2007
1509
RequestHandlerClass,
2008
1510
interface = interface,
2009
use_ipv6 = use_ipv6,
2010
socketfd = socketfd)
1511
use_ipv6 = use_ipv6)
2011
1512
def server_activate(self):
2012
1513
if self.enabled:
2013
1514
return socketserver.TCPServer.server_activate(self)
2015
1515
def enable(self):
2016
1516
self.enabled = True
2018
def add_pipe(self, parent_pipe, proc):
1517
def add_pipe(self, parent_pipe):
2019
1518
# Call "handle_ipc" for both data and EOF events
2020
1519
gobject.io_add_watch(parent_pipe.fileno(),
2021
1520
gobject.IO_IN | gobject.IO_HUP,
2022
1521
functools.partial(self.handle_ipc,
1522
parent_pipe = parent_pipe))
2027
1524
def handle_ipc(self, source, condition, parent_pipe=None,
2028
proc = None, client_object=None):
2029
# error, or the other end of multiprocessing.Pipe has closed
2030
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2031
# Wait for other process to exit
1525
client_object=None):
1527
gobject.IO_IN: "IN", # There is data to read.
1528
gobject.IO_OUT: "OUT", # Data can be written (without
1530
gobject.IO_PRI: "PRI", # There is urgent data to read.
1531
gobject.IO_ERR: "ERR", # Error condition.
1532
gobject.IO_HUP: "HUP" # Hung up (the connection has been
1533
# broken, usually for pipes and
1536
conditions_string = ' | '.join(name
1538
condition_names.iteritems()
1539
if cond & condition)
1540
# error or the other end of multiprocessing.Pipe has closed
1541
if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
2035
1544
# Read a request from the child
2049
1558
"dress: %s", fpr, address)
2050
1559
if self.use_dbus:
2051
1560
# Emit D-Bus signal
2052
mandos_dbus_service.ClientNotFound(fpr,
1561
mandos_dbus_service.ClientNotFound(fpr, address[0])
2054
1562
parent_pipe.send(False)
2057
1565
gobject.io_add_watch(parent_pipe.fileno(),
2058
1566
gobject.IO_IN | gobject.IO_HUP,
2059
1567
functools.partial(self.handle_ipc,
1568
parent_pipe = parent_pipe,
1569
client_object = client))
2065
1570
parent_pipe.send(True)
2066
# remove the old hook in favor of the new above hook on
1571
# remove the old hook in favor of the new above hook on same fileno
2069
1573
if command == 'funcall':
2070
1574
funcname = request[1]
2071
1575
args = request[2]
2072
1576
kwargs = request[3]
2074
parent_pipe.send(('data', getattr(client_object,
1578
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
2078
1580
if command == 'getattr':
2079
1581
attrname = request[1]
2080
1582
if callable(client_object.__getattribute__(attrname)):
2081
1583
parent_pipe.send(('function',))
2083
parent_pipe.send(('data', client_object
2084
.__getattribute__(attrname)))
1585
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
2086
1587
if command == 'setattr':
2087
1588
attrname = request[1]
2088
1589
value = request[2]
2089
1590
setattr(client_object, attrname, value)
2094
def rfc3339_duration_to_delta(duration):
2095
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2097
>>> rfc3339_duration_to_delta("P7D")
2098
datetime.timedelta(7)
2099
>>> rfc3339_duration_to_delta("PT60S")
2100
datetime.timedelta(0, 60)
2101
>>> rfc3339_duration_to_delta("PT60M")
2102
datetime.timedelta(0, 3600)
2103
>>> rfc3339_duration_to_delta("PT24H")
2104
datetime.timedelta(1)
2105
>>> rfc3339_duration_to_delta("P1W")
2106
datetime.timedelta(7)
2107
>>> rfc3339_duration_to_delta("PT5M30S")
2108
datetime.timedelta(0, 330)
2109
>>> rfc3339_duration_to_delta("P1DT3M20S")
2110
datetime.timedelta(1, 200)
2113
# Parsing an RFC 3339 duration with regular expressions is not
2114
# possible - there would have to be multiple places for the same
2115
# values, like seconds. The current code, while more esoteric, is
2116
# cleaner without depending on a parsing library. If Python had a
2117
# built-in library for parsing we would use it, but we'd like to
2118
# avoid excessive use of external libraries.
2120
# New type for defining tokens, syntax, and semantics all-in-one
2121
Token = collections.namedtuple("Token",
2122
("regexp", # To match token; if
2123
# "value" is not None,
2124
# must have a "group"
2126
"value", # datetime.timedelta or
2128
"followers")) # Tokens valid after
2130
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2131
# the "duration" ABNF definition in RFC 3339, Appendix A.
2132
token_end = Token(re.compile(r"$"), None, frozenset())
2133
token_second = Token(re.compile(r"(\d+)S"),
2134
datetime.timedelta(seconds=1),
2135
frozenset((token_end,)))
2136
token_minute = Token(re.compile(r"(\d+)M"),
2137
datetime.timedelta(minutes=1),
2138
frozenset((token_second, token_end)))
2139
token_hour = Token(re.compile(r"(\d+)H"),
2140
datetime.timedelta(hours=1),
2141
frozenset((token_minute, token_end)))
2142
token_time = Token(re.compile(r"T"),
2144
frozenset((token_hour, token_minute,
2146
token_day = Token(re.compile(r"(\d+)D"),
2147
datetime.timedelta(days=1),
2148
frozenset((token_time, token_end)))
2149
token_month = Token(re.compile(r"(\d+)M"),
2150
datetime.timedelta(weeks=4),
2151
frozenset((token_day, token_end)))
2152
token_year = Token(re.compile(r"(\d+)Y"),
2153
datetime.timedelta(weeks=52),
2154
frozenset((token_month, token_end)))
2155
token_week = Token(re.compile(r"(\d+)W"),
2156
datetime.timedelta(weeks=1),
2157
frozenset((token_end,)))
2158
token_duration = Token(re.compile(r"P"), None,
2159
frozenset((token_year, token_month,
2160
token_day, token_time,
2162
# Define starting values
2163
value = datetime.timedelta() # Value so far
2165
followers = frozenset(token_duration,) # Following valid tokens
2166
s = duration # String left to parse
2167
# Loop until end token is found
2168
while found_token is not token_end:
2169
# Search for any currently valid tokens
2170
for token in followers:
2171
match = token.regexp.match(s)
2172
if match is not None:
2174
if token.value is not None:
2175
# Value found, parse digits
2176
factor = int(match.group(1), 10)
2177
# Add to value so far
2178
value += factor * token.value
2179
# Strip token from string
2180
s = token.regexp.sub("", s, 1)
2183
# Set valid next tokens
2184
followers = found_token.followers
2187
# No currently valid tokens were found
2188
raise ValueError("Invalid RFC 3339 duration")
2193
1595
def string_to_delta(interval):
2194
1596
"""Parse a string and return a datetime.timedelta
2463
1856
.gnutls_global_set_log_function(debug_gnutls))
2465
1858
# Redirect stdin so all checkers get /dev/null
2466
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
1859
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2467
1860
os.dup2(null, sys.stdin.fileno())
1864
# No console logging
1865
logger.removeHandler(console)
2471
1867
# Need to fork before connecting to D-Bus
2473
1869
# Close all input and output, do double fork, etc.
2476
# multiprocessing will use threads, so before we use gobject we
2477
# need to inform gobject that threads will be used.
2478
gobject.threads_init()
2480
1872
global main_loop
2481
1873
# From the Avahi example code
2482
DBusGMainLoop(set_as_default=True)
1874
DBusGMainLoop(set_as_default=True )
2483
1875
main_loop = gobject.MainLoop()
2484
1876
bus = dbus.SystemBus()
2485
1877
# End of Avahi example code
2488
bus_name = dbus.service.BusName("se.recompile.Mandos",
1880
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2489
1881
bus, do_not_queue=True)
2490
old_bus_name = (dbus.service.BusName
2491
("se.bsnet.fukt.Mandos", bus,
2493
1882
except dbus.exceptions.NameExistsException as e:
2494
logger.error("Disabling D-Bus:", exc_info=e)
1883
logger.error(unicode(e) + ", disabling D-Bus")
2495
1884
use_dbus = False
2496
1885
server_settings["use_dbus"] = False
2497
1886
tcp_server.use_dbus = False
2498
1887
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2499
service = AvahiServiceToSyslog(name =
2500
server_settings["servicename"],
2501
servicetype = "_mandos._tcp",
2502
protocol = protocol, bus = bus)
1888
service = AvahiService(name = server_settings["servicename"],
1889
servicetype = "_mandos._tcp",
1890
protocol = protocol, bus = bus)
2503
1891
if server_settings["interface"]:
2504
1892
service.interface = (if_nametoindex
2505
1893
(str(server_settings["interface"])))
2510
1898
client_class = Client
2512
1900
client_class = functools.partial(ClientDBus, bus = bus)
2514
client_settings = Client.config_parser(client_config)
2515
old_client_settings = {}
2518
# Get client data and settings from last running state.
2519
if server_settings["restore"]:
2521
with open(stored_state_path, "rb") as stored_state:
2522
clients_data, old_client_settings = (pickle.load
2524
os.remove(stored_state_path)
2525
except IOError as e:
2526
if e.errno == errno.ENOENT:
2527
logger.warning("Could not load persistent state: {0}"
2528
.format(os.strerror(e.errno)))
2530
logger.critical("Could not load persistent state:",
2533
except EOFError as e:
2534
logger.warning("Could not load persistent state: "
2535
"EOFError:", exc_info=e)
2537
with PGPEngine() as pgp:
2538
for client_name, client in clients_data.iteritems():
2539
# Decide which value to use after restoring saved state.
2540
# We have three different values: Old config file,
2541
# new config file, and saved state.
2542
# New config value takes precedence if it differs from old
2543
# config value, otherwise use saved state.
2544
for name, value in client_settings[client_name].items():
2546
# For each value in new config, check if it
2547
# differs from the old config value (Except for
2548
# the "secret" attribute)
2549
if (name != "secret" and
2550
value != old_client_settings[client_name]
2552
client[name] = value
2556
# Clients who has passed its expire date can still be
2557
# enabled if its last checker was successful. Clients
2558
# whose checker succeeded before we stored its state is
2559
# assumed to have successfully run all checkers during
2561
if client["enabled"]:
2562
if datetime.datetime.utcnow() >= client["expires"]:
2563
if not client["last_checked_ok"]:
2565
"disabling client {0} - Client never "
2566
"performed a successful checker"
2567
.format(client_name))
2568
client["enabled"] = False
2569
elif client["last_checker_status"] != 0:
2571
"disabling client {0} - Client "
2572
"last checker failed with error code {1}"
2573
.format(client_name,
2574
client["last_checker_status"]))
2575
client["enabled"] = False
2577
client["expires"] = (datetime.datetime
2579
+ client["timeout"])
2580
logger.debug("Last checker succeeded,"
2581
" keeping {0} enabled"
2582
.format(client_name))
1901
def client_config_items(config, section):
1902
special_settings = {
1903
"approved_by_default":
1904
lambda: config.getboolean(section,
1905
"approved_by_default"),
1907
for name, value in config.items(section):
2584
client["secret"] = (
2585
pgp.decrypt(client["encrypted_secret"],
2586
client_settings[client_name]
2589
# If decryption fails, we use secret from new settings
2590
logger.debug("Failed to decrypt {0} old secret"
2591
.format(client_name))
2592
client["secret"] = (
2593
client_settings[client_name]["secret"])
2595
# Add/remove clients based on new changes made to config
2596
for client_name in (set(old_client_settings)
2597
- set(client_settings)):
2598
del clients_data[client_name]
2599
for client_name in (set(client_settings)
2600
- set(old_client_settings)):
2601
clients_data[client_name] = client_settings[client_name]
2603
# Create all client objects
2604
for client_name, client in clients_data.iteritems():
2605
tcp_server.clients[client_name] = client_class(
2606
name = client_name, settings = client)
1909
yield (name, special_settings[name]())
1913
tcp_server.clients.update(set(
1914
client_class(name = section,
1915
config= dict(client_config_items(
1916
client_config, section)))
1917
for section in client_config.sections()))
2608
1918
if not tcp_server.clients:
2609
1919
logger.warning("No clients defined")
2612
if pidfile is not None:
2616
pidfile.write(str(pid) + "\n".encode("utf-8"))
2618
logger.error("Could not write to file %r with PID %d",
1925
pidfile.write(str(pid) + "\n".encode("utf-8"))
1928
logger.error("Could not write to file %r with PID %d",
1931
# "pidfile" was never created
2621
1933
del pidfilename
1935
signal.signal(signal.SIGINT, signal.SIG_IGN)
2623
1937
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2624
1938
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2627
@alternate_dbus_interfaces({"se.recompile.Mandos":
2628
"se.bsnet.fukt.Mandos"})
2629
class MandosDBusService(DBusObjectWithProperties):
1941
class MandosDBusService(dbus.service.Object):
2630
1942
"""A D-Bus proxy object"""
2631
1943
def __init__(self):
2632
1944
dbus.service.Object.__init__(self, bus, "/")
2633
_interface = "se.recompile.Mandos"
2635
@dbus_interface_annotations(_interface)
2637
return { "org.freedesktop.DBus.Property"
2638
".EmitsChangedSignal":
1945
_interface = "se.bsnet.fukt.Mandos"
2641
1947
@dbus.service.signal(_interface, signature="o")
2642
1948
def ClientAdded(self, objpath):
2691
1996
"Cleanup function; run on exit"
2692
1997
service.cleanup()
2694
multiprocessing.active_children()
2695
if not (tcp_server.clients or client_settings):
2698
# Store client before exiting. Secrets are encrypted with key
2699
# based on what config file has. If config file is
2700
# removed/edited, old secret will thus be unrecovable.
2702
with PGPEngine() as pgp:
2703
for client in tcp_server.clients.itervalues():
2704
key = client_settings[client.name]["secret"]
2705
client.encrypted_secret = pgp.encrypt(client.secret,
2709
# A list of attributes that can not be pickled
2711
exclude = set(("bus", "changedstate", "secret",
2713
for name, typ in (inspect.getmembers
2714
(dbus.service.Object)):
2717
client_dict["encrypted_secret"] = (client
2719
for attr in client.client_structure:
2720
if attr not in exclude:
2721
client_dict[attr] = getattr(client, attr)
2723
clients[client.name] = client_dict
2724
del client_settings[client.name]["secret"]
2727
with (tempfile.NamedTemporaryFile
2728
(mode='wb', suffix=".pickle", prefix='clients-',
2729
dir=os.path.dirname(stored_state_path),
2730
delete=False)) as stored_state:
2731
pickle.dump((clients, client_settings), stored_state)
2732
tempname=stored_state.name
2733
os.rename(tempname, stored_state_path)
2734
except (IOError, OSError) as e:
2740
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2741
logger.warning("Could not save persistent state: {0}"
2742
.format(os.strerror(e.errno)))
2744
logger.warning("Could not save persistent state:",
2748
# Delete all clients, and settings from config
2749
1999
while tcp_server.clients:
2750
name, client = tcp_server.clients.popitem()
2000
client = tcp_server.clients.pop()
2752
2002
client.remove_from_connection()
2003
client.disable_hook = None
2753
2004
# Don't signal anything except ClientRemoved
2754
2005
client.disable(quiet=True)
2756
2007
# Emit D-Bus signal
2757
mandos_dbus_service.ClientRemoved(client
2008
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2760
client_settings.clear()
2762
2011
atexit.register(cleanup)
2764
for client in tcp_server.clients.itervalues():
2013
for client in tcp_server.clients:
2766
2015
# Emit D-Bus signal
2767
2016
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2768
# Need to initiate checking of clients
2770
client.init_checker()
2772
2019
tcp_server.enable()
2773
2020
tcp_server.server_activate()