380
361
def server_state_changed(self, state, error=None):
381
362
"""Derived from the Avahi example code"""
382
363
logger.debug("Avahi server state change: %i", state)
384
avahi.SERVER_INVALID: "Zeroconf server invalid",
385
avahi.SERVER_REGISTERING: None,
386
avahi.SERVER_COLLISION: "Zeroconf server name collision",
387
avahi.SERVER_FAILURE: "Zeroconf server failure",
364
bad_states = { avahi.SERVER_INVALID:
365
"Zeroconf server invalid",
366
avahi.SERVER_REGISTERING: None,
367
avahi.SERVER_COLLISION:
368
"Zeroconf server name collision",
369
avahi.SERVER_FAILURE:
370
"Zeroconf server failure" }
389
371
if state in bad_states:
390
372
if bad_states[state] is not None:
391
373
if error is None:
429
400
def rename(self, *args, **kwargs):
430
401
"""Add the new name to the syslog messages"""
431
402
ret = AvahiService.rename(self, *args, **kwargs)
432
syslogger.setFormatter(logging.Formatter(
433
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
403
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
405
' %(levelname)s: %(message)s'
437
def call_pipe(connection, # : multiprocessing.Connection
438
func, *args, **kwargs):
439
"""This function is meant to be called by multiprocessing.Process
441
This function runs func(*args, **kwargs), and writes the resulting
442
return value on the provided multiprocessing.Connection.
444
connection.send(func(*args, **kwargs))
447
410
class Client(object):
448
411
"""A representation of a client host served by this server.
495
456
"fingerprint", "host", "interval",
496
457
"last_approval_request", "last_checked_ok",
497
458
"last_enabled", "name", "timeout")
500
"extended_timeout": "PT15M",
502
"checker": "fping -q -- %%(host)s",
504
"approval_delay": "PT0S",
505
"approval_duration": "PT1S",
506
"approved_by_default": "True",
459
client_defaults = { "timeout": "PT5M",
460
"extended_timeout": "PT15M",
462
"checker": "fping -q -- %%(host)s",
464
"approval_delay": "PT0S",
465
"approval_duration": "PT1S",
466
"approved_by_default": "True",
511
471
def config_parser(config):
589
549
self.current_checker_command = None
590
550
self.approved = None
591
551
self.approvals_pending = 0
592
self.changedstate = multiprocessing_manager.Condition(
593
multiprocessing_manager.Lock())
594
self.client_structure = [attr
595
for attr in self.__dict__.iterkeys()
552
self.changedstate = (multiprocessing_manager
553
.Condition(multiprocessing_manager
555
self.client_structure = [attr for attr in
556
self.__dict__.iterkeys()
596
557
if not attr.startswith("_")]
597
558
self.client_structure.append("client_structure")
599
for name, t in inspect.getmembers(
600
type(self), lambda obj: isinstance(obj, property)):
560
for name, t in inspect.getmembers(type(self),
601
564
if not name.startswith("_"):
602
565
self.client_structure.append(name)
645
608
# and every interval from then on.
646
609
if self.checker_initiator_tag is not None:
647
610
gobject.source_remove(self.checker_initiator_tag)
648
self.checker_initiator_tag = gobject.timeout_add(
649
int(self.interval.total_seconds() * 1000),
611
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
651
615
# Schedule a disable() when 'timeout' has passed
652
616
if self.disable_initiator_tag is not None:
653
617
gobject.source_remove(self.disable_initiator_tag)
654
self.disable_initiator_tag = gobject.timeout_add(
655
int(self.timeout.total_seconds() * 1000), self.disable)
618
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
656
622
# Also start a new checker *right now*.
657
623
self.start_checker()
659
def checker_callback(self, source, condition, connection,
625
def checker_callback(self, pid, condition, command):
661
626
"""The checker has completed, so take appropriate actions."""
662
627
self.checker_callback_tag = None
663
628
self.checker = None
664
# Read return code from connection (see call_pipe)
665
returncode = connection.recv()
669
self.last_checker_status = returncode
670
self.last_checker_signal = None
629
if os.WIFEXITED(condition):
630
self.last_checker_status = os.WEXITSTATUS(condition)
671
631
if self.last_checker_status == 0:
672
632
logger.info("Checker for %(name)s succeeded",
674
634
self.checked_ok()
676
logger.info("Checker for %(name)s failed", vars(self))
636
logger.info("Checker for %(name)s failed",
678
639
self.last_checker_status = -1
679
self.last_checker_signal = -returncode
680
640
logger.warning("Checker for %(name)s crashed?",
684
643
def checked_ok(self):
685
644
"""Assert that the client has been seen, alive and well."""
686
645
self.last_checked_ok = datetime.datetime.utcnow()
687
646
self.last_checker_status = 0
688
self.last_checker_signal = None
689
647
self.bump_timeout()
691
649
def bump_timeout(self, timeout=None):
717
676
# than 'timeout' for the client to be disabled, which is as it
720
if self.checker is not None and not self.checker.is_alive():
721
logger.warning("Checker was not alive; joining")
679
# If a checker exists, make sure it is not a zombie
681
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
682
except AttributeError:
684
except OSError as error:
685
if error.errno != errno.ECHILD:
689
logger.warning("Checker was a zombie")
690
gobject.source_remove(self.checker_callback_tag)
691
self.checker_callback(pid, status,
692
self.current_checker_command)
724
693
# Start a new checker if needed
725
694
if self.checker is None:
726
695
# Escape attributes for the shell
728
attr: re.escape(str(getattr(self, attr)))
729
for attr in self.runtime_expansions }
696
escaped_attrs = { attr:
697
re.escape(str(getattr(self, attr)))
698
for attr in self.runtime_expansions }
731
700
command = self.checker_command % escaped_attrs
732
701
except TypeError as error:
733
702
logger.error('Could not format string "%s"',
734
self.checker_command,
703
self.checker_command, exc_info=error)
704
return True # Try again later
705
self.current_checker_command = command
707
logger.info("Starting checker %r for %s",
709
# We don't need to redirect stdout and stderr, since
710
# in normal mode, that is already done by daemon(),
711
# and in debug mode we don't want to. (Stdin is
712
# always replaced by /dev/null.)
713
# The exception is when not debugging but nevertheless
714
# running in the foreground; use the previously
717
if (not self.server_settings["debug"]
718
and self.server_settings["foreground"]):
719
popen_args.update({"stdout": wnull,
721
self.checker = subprocess.Popen(command,
725
except OSError as error:
726
logger.error("Failed to start subprocess",
736
return True # Try again later
737
self.current_checker_command = command
738
logger.info("Starting checker %r for %s", command,
740
# We don't need to redirect stdout and stderr, since
741
# in normal mode, that is already done by daemon(),
742
# and in debug mode we don't want to. (Stdin is
743
# always replaced by /dev/null.)
744
# The exception is when not debugging but nevertheless
745
# running in the foreground; use the previously
747
popen_args = { "close_fds": True,
750
if (not self.server_settings["debug"]
751
and self.server_settings["foreground"]):
752
popen_args.update({"stdout": wnull,
754
pipe = multiprocessing.Pipe(duplex = False)
755
self.checker = multiprocessing.Process(
757
args = (pipe[1], subprocess.call, command),
760
self.checker_callback_tag = gobject.io_add_watch(
761
pipe[0].fileno(), gobject.IO_IN,
762
self.checker_callback, pipe[0], command)
729
self.checker_callback_tag = (gobject.child_watch_add
731
self.checker_callback,
733
# The checker may have completed before the gobject
734
# watch was added. Check for this.
736
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
737
except OSError as error:
738
if error.errno == errno.ECHILD:
739
# This should never happen
740
logger.error("Child process vanished",
745
gobject.source_remove(self.checker_callback_tag)
746
self.checker_callback(pid, status, command)
763
747
# Re-run this periodically if run by gobject.timeout_add
890
871
def _get_all_dbus_things(self, thing):
891
872
"""Returns a generator of (name, attribute) pairs
893
return ((getattr(athing.__get__(self), "_dbus_name", name),
874
return ((getattr(athing.__get__(self), "_dbus_name",
894
876
athing.__get__(self))
895
877
for cls in self.__class__.__mro__
896
878
for name, athing in
897
inspect.getmembers(cls, self._is_dbus_thing(thing)))
899
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
901
path_keyword = 'object_path',
902
connection_keyword = 'connection')
903
def Introspect(self, object_path, connection):
904
"""Overloading of standard D-Bus method.
906
Inserts annotation tags on methods and signals.
908
xmlstring = dbus.service.Object.Introspect(self, object_path,
911
document = xml.dom.minidom.parseString(xmlstring)
913
for if_tag in document.getElementsByTagName("interface"):
914
# Add annotation tags
915
for typ in ("method", "signal"):
916
for tag in if_tag.getElementsByTagName(typ):
918
for name, prop in (self.
919
_get_all_dbus_things(typ)):
920
if (name == tag.getAttribute("name")
921
and prop._dbus_interface
922
== if_tag.getAttribute("name")):
923
annots.update(getattr(
924
prop, "_dbus_annotations", {}))
925
for name, value in annots.items():
926
ann_tag = document.createElement(
928
ann_tag.setAttribute("name", name)
929
ann_tag.setAttribute("value", value)
930
tag.appendChild(ann_tag)
931
# Add interface annotation tags
932
for annotation, value in dict(
933
itertools.chain.from_iterable(
934
annotations().items()
935
for name, annotations
936
in self._get_all_dbus_things("interface")
937
if name == if_tag.getAttribute("name")
939
ann_tag = document.createElement("annotation")
940
ann_tag.setAttribute("name", annotation)
941
ann_tag.setAttribute("value", value)
942
if_tag.appendChild(ann_tag)
943
# Fix argument name for the Introspect method itself
944
if (if_tag.getAttribute("name")
945
== dbus.INTROSPECTABLE_IFACE):
946
for cn in if_tag.getElementsByTagName("method"):
947
if cn.getAttribute("name") == "Introspect":
948
for arg in cn.getElementsByTagName("arg"):
949
if (arg.getAttribute("direction")
951
arg.setAttribute("name",
953
xmlstring = document.toxml("utf-8")
955
except (AttributeError, xml.dom.DOMException,
956
xml.parsers.expat.ExpatError) as error:
957
logger.error("Failed to override Introspection method",
962
class DBusObjectWithProperties(DBusObjectWithAnnotations):
963
"""A D-Bus object with properties.
965
Classes inheriting from this can use the dbus_service_property
966
decorator to expose methods as D-Bus properties. It exposes the
967
standard Get(), Set(), and GetAll() methods on the D-Bus.
879
inspect.getmembers(cls,
880
self._is_dbus_thing(thing)))
970
882
def _get_dbus_property(self, interface_name, property_name):
971
883
"""Returns a bound method if one exists which is a D-Bus
972
884
property with the specified name and interface.
974
for cls in self.__class__.__mro__:
975
for name, value in inspect.getmembers(
976
cls, self._is_dbus_thing("property")):
886
for cls in self.__class__.__mro__:
887
for name, value in (inspect.getmembers
889
self._is_dbus_thing("property"))):
977
890
if (value._dbus_name == property_name
978
891
and value._dbus_interface == interface_name):
979
892
return value.__get__(self)
981
894
# No such property
982
raise DBusPropertyNotFound("{}:{}.{}".format(
983
self.dbus_object_path, interface_name, property_name))
986
def _get_all_interface_names(cls):
987
"""Get a sequence of all interfaces supported by an object"""
988
return (name for name in set(getattr(getattr(x, attr),
989
"_dbus_interface", None)
990
for x in (inspect.getmro(cls))
994
@dbus.service.method(dbus.PROPERTIES_IFACE,
895
raise DBusPropertyNotFound(self.dbus_object_path + ":"
896
+ interface_name + "."
899
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
996
900
out_signature="v")
997
901
def Get(self, interface_name, property_name):
998
902
"""Standard D-Bus property Get() method, see D-Bus standard.
1067
970
Inserts property tags and interface annotation tags.
1069
xmlstring = DBusObjectWithAnnotations.Introspect(self,
972
xmlstring = dbus.service.Object.Introspect(self, object_path,
1073
975
document = xml.dom.minidom.parseString(xmlstring)
1075
976
def make_tag(document, name, prop):
1076
977
e = document.createElement("property")
1077
978
e.setAttribute("name", name)
1078
979
e.setAttribute("type", prop._dbus_signature)
1079
980
e.setAttribute("access", prop._dbus_access)
1082
982
for if_tag in document.getElementsByTagName("interface"):
1083
983
# Add property tags
1084
984
for tag in (make_tag(document, name, prop)
1087
987
if prop._dbus_interface
1088
988
== if_tag.getAttribute("name")):
1089
989
if_tag.appendChild(tag)
1090
# Add annotation tags for properties
1091
for tag in if_tag.getElementsByTagName("property"):
1093
for name, prop in self._get_all_dbus_things(
1095
if (name == tag.getAttribute("name")
1096
and prop._dbus_interface
1097
== if_tag.getAttribute("name")):
1098
annots.update(getattr(
1099
prop, "_dbus_annotations", {}))
1100
for name, value in annots.items():
1101
ann_tag = document.createElement(
1103
ann_tag.setAttribute("name", name)
1104
ann_tag.setAttribute("value", value)
1105
tag.appendChild(ann_tag)
990
# Add annotation tags
991
for typ in ("method", "signal", "property"):
992
for tag in if_tag.getElementsByTagName(typ):
994
for name, prop in (self.
995
_get_all_dbus_things(typ)):
996
if (name == tag.getAttribute("name")
997
and prop._dbus_interface
998
== if_tag.getAttribute("name")):
999
annots.update(getattr
1001
"_dbus_annotations",
1003
for name, value in annots.items():
1004
ann_tag = document.createElement(
1006
ann_tag.setAttribute("name", name)
1007
ann_tag.setAttribute("value", value)
1008
tag.appendChild(ann_tag)
1009
# Add interface annotation tags
1010
for annotation, value in dict(
1011
itertools.chain.from_iterable(
1012
annotations().items()
1013
for name, annotations in
1014
self._get_all_dbus_things("interface")
1015
if name == if_tag.getAttribute("name")
1017
ann_tag = document.createElement("annotation")
1018
ann_tag.setAttribute("name", annotation)
1019
ann_tag.setAttribute("value", value)
1020
if_tag.appendChild(ann_tag)
1106
1021
# Add the names to the return values for the
1107
1022
# "org.freedesktop.DBus.Properties" methods
1108
1023
if (if_tag.getAttribute("name")
1126
1041
exc_info=error)
1127
1042
return xmlstring
1130
dbus.OBJECT_MANAGER_IFACE
1131
except AttributeError:
1132
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1134
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1135
"""A D-Bus object with an ObjectManager.
1137
Classes inheriting from this exposes the standard
1138
GetManagedObjects call and the InterfacesAdded and
1139
InterfacesRemoved signals on the standard
1140
"org.freedesktop.DBus.ObjectManager" interface.
1142
Note: No signals are sent automatically; they must be sent
1145
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1146
out_signature = "a{oa{sa{sv}}}")
1147
def GetManagedObjects(self):
1148
"""This function must be overridden"""
1149
raise NotImplementedError()
1151
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1152
signature = "oa{sa{sv}}")
1153
def InterfacesAdded(self, object_path, interfaces_and_properties):
1156
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1157
def InterfacesRemoved(self, object_path, interfaces):
1160
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1161
out_signature = "s",
1162
path_keyword = 'object_path',
1163
connection_keyword = 'connection')
1164
def Introspect(self, object_path, connection):
1165
"""Overloading of standard D-Bus method.
1167
Override return argument name of GetManagedObjects to be
1168
"objpath_interfaces_and_properties"
1170
xmlstring = DBusObjectWithAnnotations.Introspect(self,
1174
document = xml.dom.minidom.parseString(xmlstring)
1176
for if_tag in document.getElementsByTagName("interface"):
1177
# Fix argument name for the GetManagedObjects method
1178
if (if_tag.getAttribute("name")
1179
== dbus.OBJECT_MANAGER_IFACE):
1180
for cn in if_tag.getElementsByTagName("method"):
1181
if (cn.getAttribute("name")
1182
== "GetManagedObjects"):
1183
for arg in cn.getElementsByTagName("arg"):
1184
if (arg.getAttribute("direction")
1188
"objpath_interfaces"
1190
xmlstring = document.toxml("utf-8")
1192
except (AttributeError, xml.dom.DOMException,
1193
xml.parsers.expat.ExpatError) as error:
1194
logger.error("Failed to override Introspection method",
1198
1045
def datetime_to_dbus(dt, variant_level=0):
1199
1046
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1201
1048
return dbus.String("", variant_level = variant_level)
1202
return dbus.String(dt.isoformat(), variant_level=variant_level)
1049
return dbus.String(dt.isoformat(),
1050
variant_level=variant_level)
1205
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1236
1083
# Ignore non-D-Bus attributes, and D-Bus attributes
1237
1084
# with the wrong interface name
1238
1085
if (not hasattr(attribute, "_dbus_interface")
1239
or not attribute._dbus_interface.startswith(
1240
orig_interface_name)):
1086
or not attribute._dbus_interface
1087
.startswith(orig_interface_name)):
1242
1089
# Create an alternate D-Bus interface name based on
1243
1090
# the current name
1244
alt_interface = attribute._dbus_interface.replace(
1245
orig_interface_name, alt_interface_name)
1091
alt_interface = (attribute._dbus_interface
1092
.replace(orig_interface_name,
1093
alt_interface_name))
1246
1094
interface_names.add(alt_interface)
1247
1095
# Is this a D-Bus signal?
1248
1096
if getattr(attribute, "_dbus_is_signal", False):
1249
if sys.version_info.major == 2:
1250
# Extract the original non-method undecorated
1251
# function by black magic
1252
nonmethod_func = (dict(
1097
# Extract the original non-method undecorated
1098
# function by black magic
1099
nonmethod_func = (dict(
1253
1100
zip(attribute.func_code.co_freevars,
1254
attribute.__closure__))
1255
["func"].cell_contents)
1257
nonmethod_func = attribute
1101
attribute.__closure__))["func"]
1258
1103
# Create a new, but exactly alike, function
1259
1104
# object, and decorate it to be a new D-Bus signal
1260
1105
# with the alternate D-Bus interface name
1261
if sys.version_info.major == 2:
1262
new_function = types.FunctionType(
1263
nonmethod_func.func_code,
1264
nonmethod_func.func_globals,
1265
nonmethod_func.func_name,
1266
nonmethod_func.func_defaults,
1267
nonmethod_func.func_closure)
1269
new_function = types.FunctionType(
1270
nonmethod_func.__code__,
1271
nonmethod_func.__globals__,
1272
nonmethod_func.__name__,
1273
nonmethod_func.__defaults__,
1274
nonmethod_func.__closure__)
1275
new_function = (dbus.service.signal(
1277
attribute._dbus_signature)(new_function))
1106
new_function = (dbus.service.signal
1108
attribute._dbus_signature)
1109
(types.FunctionType(
1110
nonmethod_func.func_code,
1111
nonmethod_func.func_globals,
1112
nonmethod_func.func_name,
1113
nonmethod_func.func_defaults,
1114
nonmethod_func.func_closure)))
1278
1115
# Copy annotations, if any
1280
new_function._dbus_annotations = dict(
1281
attribute._dbus_annotations)
1117
new_function._dbus_annotations = (
1118
dict(attribute._dbus_annotations))
1282
1119
except AttributeError:
1284
1121
# Define a creator of a function to call both the
1311
1141
# object. Decorate it to be a new D-Bus method
1312
1142
# with the alternate D-Bus interface name. Add it
1313
1143
# to the class.
1315
dbus.service.method(
1317
attribute._dbus_in_signature,
1318
attribute._dbus_out_signature)
1319
(types.FunctionType(attribute.func_code,
1320
attribute.func_globals,
1321
attribute.func_name,
1322
attribute.func_defaults,
1323
attribute.func_closure)))
1144
attr[attrname] = (dbus.service.method
1146
attribute._dbus_in_signature,
1147
attribute._dbus_out_signature)
1149
(attribute.func_code,
1150
attribute.func_globals,
1151
attribute.func_name,
1152
attribute.func_defaults,
1153
attribute.func_closure)))
1324
1154
# Copy annotations, if any
1326
attr[attrname]._dbus_annotations = dict(
1327
attribute._dbus_annotations)
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1328
1158
except AttributeError:
1330
1160
# Is this a D-Bus property?
1333
1163
# object, and decorate it to be a new D-Bus
1334
1164
# property with the alternate D-Bus interface
1335
1165
# name. Add it to the class.
1336
attr[attrname] = (dbus_service_property(
1337
alt_interface, attribute._dbus_signature,
1338
attribute._dbus_access,
1339
attribute._dbus_get_args_options
1341
(types.FunctionType(
1342
attribute.func_code,
1343
attribute.func_globals,
1344
attribute.func_name,
1345
attribute.func_defaults,
1346
attribute.func_closure)))
1166
attr[attrname] = (dbus_service_property
1168
attribute._dbus_signature,
1169
attribute._dbus_access,
1171
._dbus_get_args_options
1174
(attribute.func_code,
1175
attribute.func_globals,
1176
attribute.func_name,
1177
attribute.func_defaults,
1178
attribute.func_closure)))
1347
1179
# Copy annotations, if any
1349
attr[attrname]._dbus_annotations = dict(
1350
attribute._dbus_annotations)
1181
attr[attrname]._dbus_annotations = (
1182
dict(attribute._dbus_annotations))
1351
1183
except AttributeError:
1353
1185
# Is this a D-Bus interface?
1434
1264
variant_level: D-Bus variant level. Default: 1
1436
1266
attrname = "_{}".format(dbus_name)
1438
1267
def setter(self, value):
1439
1268
if hasattr(self, "dbus_object_path"):
1440
1269
if (not hasattr(self, attrname) or
1441
1270
type_func(getattr(self, attrname, None))
1442
1271
!= type_func(value)):
1443
1272
if invalidate_only:
1444
self.PropertiesChanged(
1445
_interface, dbus.Dictionary(),
1446
dbus.Array((dbus_name, )))
1273
self.PropertiesChanged(_interface,
1448
dbus_value = transform_func(
1450
variant_level = variant_level)
1278
dbus_value = transform_func(type_func(value),
1451
1281
self.PropertyChanged(dbus.String(dbus_name),
1453
self.PropertiesChanged(
1455
dbus.Dictionary({ dbus.String(dbus_name):
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1458
1287
setattr(self, attrname, value)
1460
1289
return property(lambda self: getattr(self, attrname), setter)
1477
1306
datetime_to_dbus, "LastApprovalRequest")
1478
1307
approved_by_default = notifychangeproperty(dbus.Boolean,
1479
1308
"ApprovedByDefault")
1480
approval_delay = notifychangeproperty(
1481
dbus.UInt64, "ApprovalDelay",
1482
type_func = lambda td: td.total_seconds() * 1000)
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1312
lambda td: td.total_seconds()
1483
1314
approval_duration = notifychangeproperty(
1484
1315
dbus.UInt64, "ApprovalDuration",
1485
1316
type_func = lambda td: td.total_seconds() * 1000)
1486
1317
host = notifychangeproperty(dbus.String, "Host")
1487
timeout = notifychangeproperty(
1488
dbus.UInt64, "Timeout",
1489
type_func = lambda td: td.total_seconds() * 1000)
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1490
1321
extended_timeout = notifychangeproperty(
1491
1322
dbus.UInt64, "ExtendedTimeout",
1492
1323
type_func = lambda td: td.total_seconds() * 1000)
1493
interval = notifychangeproperty(
1494
dbus.UInt64, "Interval",
1495
type_func = lambda td: td.total_seconds() * 1000)
1324
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1496
1329
checker_command = notifychangeproperty(dbus.String, "Checker")
1497
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1498
1331
invalidate_only=True)
1508
1341
DBusObjectWithProperties.__del__(self, *args, **kwargs)
1509
1342
Client.__del__(self, *args, **kwargs)
1511
def checker_callback(self, source, condition,
1512
connection, command, *args, **kwargs):
1513
ret = Client.checker_callback(self, source, condition,
1514
connection, command, *args,
1516
exitstatus = self.last_checker_status
1344
def checker_callback(self, pid, condition, command,
1346
self.checker_callback_tag = None
1348
if os.WIFEXITED(condition):
1349
exitstatus = os.WEXITSTATUS(condition)
1518
1350
# Emit D-Bus signal
1519
1351
self.CheckerCompleted(dbus.Int16(exitstatus),
1520
# This is specific to GNU libC
1521
dbus.Int64(exitstatus << 8),
1352
dbus.Int64(condition),
1522
1353
dbus.String(command))
1524
1355
# Emit D-Bus signal
1525
1356
self.CheckerCompleted(dbus.Int16(-1),
1527
# This is specific to GNU libC
1529
| self.last_checker_signal),
1357
dbus.Int64(condition),
1530
1358
dbus.String(command))
1360
return Client.checker_callback(self, pid, condition, command,
1533
1363
def start_checker(self, *args, **kwargs):
1534
1364
old_checker_pid = getattr(self.checker, "pid", None)
1672
1495
self.approval_duration = datetime.timedelta(0, 0, 0, value)
1674
1497
# Name - property
1676
{"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1677
1498
@dbus_service_property(_interface, signature="s", access="read")
1678
1499
def Name_dbus_property(self):
1679
1500
return dbus.String(self.name)
1681
1502
# Fingerprint - property
1683
{"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1684
1503
@dbus_service_property(_interface, signature="s", access="read")
1685
1504
def Fingerprint_dbus_property(self):
1686
1505
return dbus.String(self.fingerprint)
1688
1507
# Host - property
1689
@dbus_service_property(_interface,
1508
@dbus_service_property(_interface, signature="s",
1691
1509
access="readwrite")
1692
1510
def Host_dbus_property(self, value=None):
1693
1511
if value is None: # get
2043
1847
def fingerprint(openpgp):
2044
1848
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
2045
1849
# New GnuTLS "datum" with the OpenPGP public key
2046
datum = gnutls.library.types.gnutls_datum_t(
2047
ctypes.cast(ctypes.c_char_p(openpgp),
2048
ctypes.POINTER(ctypes.c_ubyte)),
2049
ctypes.c_uint(len(openpgp)))
1850
datum = (gnutls.library.types
1851
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1854
ctypes.c_uint(len(openpgp))))
2050
1855
# New empty GnuTLS certificate
2051
1856
crt = gnutls.library.types.gnutls_openpgp_crt_t()
2052
gnutls.library.functions.gnutls_openpgp_crt_init(
1857
(gnutls.library.functions
1858
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
2054
1859
# Import the OpenPGP public key into the certificate
2055
gnutls.library.functions.gnutls_openpgp_crt_import(
2056
crt, ctypes.byref(datum),
2057
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1860
(gnutls.library.functions
1861
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1862
gnutls.library.constants
1863
.GNUTLS_OPENPGP_FMT_RAW))
2058
1864
# Verify the self signature in the key
2059
1865
crtverify = ctypes.c_uint()
2060
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
2061
crt, 0, ctypes.byref(crtverify))
1866
(gnutls.library.functions
1867
.gnutls_openpgp_crt_verify_self(crt, 0,
1868
ctypes.byref(crtverify)))
2062
1869
if crtverify.value != 0:
2063
1870
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2064
raise gnutls.errors.CertificateSecurityError(
1871
raise (gnutls.errors.CertificateSecurityError
2066
1873
# New buffer for the fingerprint
2067
1874
buf = ctypes.create_string_buffer(20)
2068
1875
buf_len = ctypes.c_size_t()
2069
1876
# Get the fingerprint from the certificate into the buffer
2070
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
2071
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1877
(gnutls.library.functions
1878
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1879
ctypes.byref(buf_len)))
2072
1880
# Deinit the certificate
2073
1881
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2074
1882
# Convert the buffer to a Python bytestring
2252
2051
def add_pipe(self, parent_pipe, proc):
2253
2052
# Call "handle_ipc" for both data and EOF events
2254
gobject.io_add_watch(
2255
parent_pipe.fileno(),
2256
gobject.IO_IN | gobject.IO_HUP,
2257
functools.partial(self.handle_ipc,
2258
parent_pipe = parent_pipe,
2053
gobject.io_add_watch(parent_pipe.fileno(),
2054
gobject.IO_IN | gobject.IO_HUP,
2055
functools.partial(self.handle_ipc,
2261
def handle_ipc(self, source, condition,
2264
client_object=None):
2060
def handle_ipc(self, source, condition, parent_pipe=None,
2061
proc = None, client_object=None):
2265
2062
# error, or the other end of multiprocessing.Pipe has closed
2266
2063
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2267
2064
# Wait for other process to exit
2354
2151
# avoid excessive use of external libraries.
2356
2153
# New type for defining tokens, syntax, and semantics all-in-one
2357
Token = collections.namedtuple("Token", (
2358
"regexp", # To match token; if "value" is not None, must have
2359
# a "group" containing digits
2360
"value", # datetime.timedelta or None
2361
"followers")) # Tokens valid after this token
2154
Token = collections.namedtuple("Token",
2155
("regexp", # To match token; if
2156
# "value" is not None,
2157
# must have a "group"
2159
"value", # datetime.timedelta or
2161
"followers")) # Tokens valid after
2362
2163
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2363
2164
# the "duration" ABNF definition in RFC 3339, Appendix A.
2364
2165
token_end = Token(re.compile(r"$"), None, frozenset())
2365
2166
token_second = Token(re.compile(r"(\d+)S"),
2366
2167
datetime.timedelta(seconds=1),
2367
frozenset((token_end, )))
2168
frozenset((token_end,)))
2368
2169
token_minute = Token(re.compile(r"(\d+)M"),
2369
2170
datetime.timedelta(minutes=1),
2370
2171
frozenset((token_second, token_end)))
2596
2396
# Override the settings from the config file with command line
2597
2397
# options, if set.
2598
2398
for option in ("interface", "address", "port", "debug",
2599
"priority", "servicename", "configdir", "use_dbus",
2600
"use_ipv6", "debuglevel", "restore", "statedir",
2601
"socket", "foreground", "zeroconf"):
2399
"priority", "servicename", "configdir",
2400
"use_dbus", "use_ipv6", "debuglevel", "restore",
2401
"statedir", "socket", "foreground", "zeroconf"):
2602
2402
value = getattr(options, option)
2603
2403
if value is not None:
2604
2404
server_settings[option] = value
2661
2463
socketfd = None
2662
2464
if server_settings["socket"] != "":
2663
2465
socketfd = server_settings["socket"]
2664
tcp_server = MandosServer(
2665
(server_settings["address"], server_settings["port"]),
2667
interface=(server_settings["interface"] or None),
2669
gnutls_priority=server_settings["priority"],
2466
tcp_server = MandosServer((server_settings["address"],
2467
server_settings["port"]),
2469
interface=(server_settings["interface"]
2473
server_settings["priority"],
2672
2476
if not foreground:
2673
2477
pidfilename = "/run/mandos.pid"
2674
2478
if not os.path.isdir("/run/."):
2675
2479
pidfilename = "/var/run/mandos.pid"
2678
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2482
pidfile = open(pidfilename, "w")
2679
2483
except IOError as e:
2680
2484
logger.error("Could not open file %r", pidfilename,
2737
2541
bus_name = dbus.service.BusName("se.recompile.Mandos",
2740
old_bus_name = dbus.service.BusName(
2741
"se.bsnet.fukt.Mandos", bus,
2743
except dbus.exceptions.DBusException as e:
2542
bus, do_not_queue=True)
2543
old_bus_name = (dbus.service.BusName
2544
("se.bsnet.fukt.Mandos", bus,
2546
except dbus.exceptions.NameExistsException as e:
2744
2547
logger.error("Disabling D-Bus:", exc_info=e)
2745
2548
use_dbus = False
2746
2549
server_settings["use_dbus"] = False
2747
2550
tcp_server.use_dbus = False
2749
2552
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2750
service = AvahiServiceToSyslog(
2751
name = server_settings["servicename"],
2752
servicetype = "_mandos._tcp",
2753
protocol = protocol,
2553
service = AvahiServiceToSyslog(name =
2554
server_settings["servicename"],
2555
servicetype = "_mandos._tcp",
2556
protocol = protocol, bus = bus)
2755
2557
if server_settings["interface"]:
2756
service.interface = if_nametoindex(
2757
server_settings["interface"].encode("utf-8"))
2558
service.interface = (if_nametoindex
2559
(server_settings["interface"]
2759
2562
global multiprocessing_manager
2760
2563
multiprocessing_manager = multiprocessing.Manager()
2779
2582
if server_settings["restore"]:
2781
2584
with open(stored_state_path, "rb") as stored_state:
2782
clients_data, old_client_settings = pickle.load(
2585
clients_data, old_client_settings = (pickle.load
2784
2587
os.remove(stored_state_path)
2785
2588
except IOError as e:
2786
2589
if e.errno == errno.ENOENT:
2787
logger.warning("Could not load persistent state:"
2788
" {}".format(os.strerror(e.errno)))
2590
logger.warning("Could not load persistent state: {}"
2591
.format(os.strerror(e.errno)))
2790
2593
logger.critical("Could not load persistent state:",
2793
2596
except EOFError as e:
2794
2597
logger.warning("Could not load persistent state: "
2598
"EOFError:", exc_info=e)
2798
2600
with PGPEngine() as pgp:
2799
2601
for client_name, client in clients_data.items():
2828
2630
if not client["last_checked_ok"]:
2829
2631
logger.warning(
2830
2632
"disabling client {} - Client never "
2831
"performed a successful checker".format(
2633
"performed a successful checker"
2634
.format(client_name))
2833
2635
client["enabled"] = False
2834
2636
elif client["last_checker_status"] != 0:
2835
2637
logger.warning(
2836
2638
"disabling client {} - Client last"
2837
" checker failed with error code"
2840
client["last_checker_status"]))
2639
" checker failed with error code {}"
2640
.format(client_name,
2641
client["last_checker_status"]))
2841
2642
client["enabled"] = False
2843
client["expires"] = (
2844
datetime.datetime.utcnow()
2845
+ client["timeout"])
2644
client["expires"] = (datetime.datetime
2646
+ client["timeout"])
2846
2647
logger.debug("Last checker succeeded,"
2847
" keeping {} enabled".format(
2648
" keeping {} enabled"
2649
.format(client_name))
2850
client["secret"] = pgp.decrypt(
2851
client["encrypted_secret"],
2852
client_settings[client_name]["secret"])
2651
client["secret"] = (
2652
pgp.decrypt(client["encrypted_secret"],
2653
client_settings[client_name]
2853
2655
except PGPError:
2854
2656
# If decryption fails, we use secret from new settings
2855
logger.debug("Failed to decrypt {} old secret".format(
2857
client["secret"] = (client_settings[client_name]
2657
logger.debug("Failed to decrypt {} old secret"
2658
.format(client_name))
2659
client["secret"] = (
2660
client_settings[client_name]["secret"])
2860
2662
# Add/remove clients based on new changes made to config
2861
2663
for client_name in (set(old_client_settings)
2891
2692
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2895
@alternate_dbus_interfaces(
2896
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2897
class MandosDBusService(DBusObjectWithObjectManager):
2695
@alternate_dbus_interfaces({"se.recompile.Mandos":
2696
"se.bsnet.fukt.Mandos"})
2697
class MandosDBusService(DBusObjectWithProperties):
2898
2698
"""A D-Bus proxy object"""
2900
2699
def __init__(self):
2901
2700
dbus.service.Object.__init__(self, bus, "/")
2903
2701
_interface = "se.recompile.Mandos"
2703
@dbus_interface_annotations(_interface)
2705
return { "org.freedesktop.DBus.Property"
2706
".EmitsChangedSignal":
2905
2709
@dbus.service.signal(_interface, signature="o")
2906
2710
def ClientAdded(self, objpath):
2915
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
2917
2719
@dbus.service.signal(_interface, signature="os")
2918
2720
def ClientRemoved(self, objpath, name):
2922
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
2924
2724
@dbus.service.method(_interface, out_signature="ao")
2925
2725
def GetAllClients(self):
2927
return dbus.Array(c.dbus_object_path for c in
2727
return dbus.Array(c.dbus_object_path
2928
2729
tcp_server.clients.itervalues())
2930
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
2932
2731
@dbus.service.method(_interface,
2933
2732
out_signature="a{oa{sv}}")
2934
2733
def GetAllClientsWithProperties(self):
2936
2735
return dbus.Dictionary(
2937
{ c.dbus_object_path: c.GetAll(
2938
"se.recompile.Mandos.Client")
2736
{ c.dbus_object_path: c.GetAll("")
2939
2737
for c in tcp_server.clients.itervalues() },
2940
2738
signature="oa{sv}")
2946
2744
if c.dbus_object_path == object_path:
2947
2745
del tcp_server.clients[c.name]
2948
2746
c.remove_from_connection()
2949
# Don't signal the disabling
2747
# Don't signal anything except ClientRemoved
2950
2748
c.disable(quiet=True)
2951
# Emit D-Bus signal for removal
2952
self.client_removed_signal(c)
2750
self.ClientRemoved(object_path, c.name)
2954
2752
raise KeyError(object_path)
2958
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
2959
out_signature = "a{oa{sa{sv}}}")
2960
def GetManagedObjects(self):
2962
return dbus.Dictionary(
2963
{ client.dbus_object_path:
2965
{ interface: client.GetAll(interface)
2967
client._get_all_interface_names()})
2968
for client in tcp_server.clients.values()})
2970
def client_added_signal(self, client):
2971
"""Send the new standard signal and the old signal"""
2973
# New standard signal
2974
self.InterfacesAdded(
2975
client.dbus_object_path,
2977
{ interface: client.GetAll(interface)
2979
client._get_all_interface_names()}))
2981
self.ClientAdded(client.dbus_object_path)
2983
def client_removed_signal(self, client):
2984
"""Send the new standard signal and the old signal"""
2986
# New standard signal
2987
self.InterfacesRemoved(
2988
client.dbus_object_path,
2989
client._get_all_interface_names())
2991
self.ClientRemoved(client.dbus_object_path,
2994
2756
mandos_dbus_service = MandosDBusService()
3032
2794
del client_settings[client.name]["secret"]
3035
with tempfile.NamedTemporaryFile(
3039
dir=os.path.dirname(stored_state_path),
3040
delete=False) as stored_state:
2797
with (tempfile.NamedTemporaryFile
2798
(mode='wb', suffix=".pickle", prefix='clients-',
2799
dir=os.path.dirname(stored_state_path),
2800
delete=False)) as stored_state:
3041
2801
pickle.dump((clients, client_settings), stored_state)
3042
tempname = stored_state.name
2802
tempname=stored_state.name
3043
2803
os.rename(tempname, stored_state_path)
3044
2804
except (IOError, OSError) as e: