11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2015 Teddy Hogeborn
15
# Copyright © 2008-2015 Björn Påhlsson
14
# Copyright © 2008-2014 Teddy Hogeborn
15
# Copyright © 2008-2014 Björn Påhlsson
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
103
91
if sys.version_info.major == 2:
107
95
stored_state_file = "clients.pickle"
109
97
logger = logging.getLogger()
113
if_nametoindex = ctypes.cdll.LoadLibrary(
114
ctypes.util.find_library("c")).if_nametoindex
101
if_nametoindex = (ctypes.cdll.LoadLibrary
102
(ctypes.util.find_library("c"))
115
104
except (OSError, AttributeError):
117
105
def if_nametoindex(interface):
118
106
"Get an interface index the hard way, i.e. using fcntl()"
119
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
128
116
"""init logger and add loglevel"""
131
syslogger = (logging.handlers.SysLogHandler(
132
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
133
address = "/dev/log"))
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
134
123
syslogger.setFormatter(logging.Formatter
135
124
('Mandos [%(process)d]: %(levelname)s:'
199
187
def encrypt(self, data, password):
200
188
passphrase = self.password_encode(password)
201
with tempfile.NamedTemporaryFile(
202
dir=self.tempdir) as passfile:
189
with tempfile.NamedTemporaryFile(dir=self.tempdir
203
191
passfile.write(passphrase)
205
193
proc = subprocess.Popen(['gpg', '--symmetric',
217
205
def decrypt(self, data, password):
218
206
passphrase = self.password_encode(password)
219
with tempfile.NamedTemporaryFile(
220
dir = self.tempdir) as passfile:
207
with tempfile.NamedTemporaryFile(dir = self.tempdir
221
209
passfile.write(passphrase)
223
211
proc = subprocess.Popen(['gpg', '--decrypt',
269
256
bus: dbus.SystemBus()
273
interface = avahi.IF_UNSPEC,
281
protocol = avahi.PROTO_UNSPEC,
259
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
260
servicetype = None, port = None, TXT = None,
261
domain = "", host = "", max_renames = 32768,
262
protocol = avahi.PROTO_UNSPEC, bus = None):
283
263
self.interface = interface
285
265
self.type = servicetype
296
276
self.entry_group_state_changed_match = None
298
def rename(self, remove=True):
299
279
"""Derived from the Avahi example code"""
300
280
if self.rename_count >= self.max_renames:
301
281
logger.critical("No suitable Zeroconf service name found"
302
282
" after %i retries, exiting.",
303
283
self.rename_count)
304
284
raise AvahiServiceError("Too many renames")
306
self.server.GetAlternativeServiceName(self.name))
307
self.rename_count += 1
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
308
287
logger.info("Changing Zeroconf service name to %r ...",
314
292
except dbus.exceptions.DBusException as error:
315
if (error.get_dbus_name()
316
== "org.freedesktop.Avahi.CollisionError"):
317
logger.info("Local Zeroconf service name collision.")
318
return self.rename(remove=False)
320
logger.critical("D-Bus Exception", exc_info=error)
293
logger.critical("D-Bus Exception", exc_info=error)
296
self.rename_count += 1
324
298
def remove(self):
325
299
"""Derived from the Avahi example code"""
380
355
def server_state_changed(self, state, error=None):
381
356
"""Derived from the Avahi example code"""
382
357
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",
358
bad_states = { avahi.SERVER_INVALID:
359
"Zeroconf server invalid",
360
avahi.SERVER_REGISTERING: None,
361
avahi.SERVER_COLLISION:
362
"Zeroconf server name collision",
363
avahi.SERVER_FAILURE:
364
"Zeroconf server failure" }
389
365
if state in bad_states:
390
366
if bad_states[state] is not None:
391
367
if error is None:
410
386
follow_name_owner_changes=True),
411
387
avahi.DBUS_INTERFACE_SERVER)
412
388
self.server.connect_to_signal("StateChanged",
413
self.server_state_changed)
389
self.server_state_changed)
414
390
self.server_state_changed(self.server.GetState())
417
393
class AvahiServiceToSyslog(AvahiService):
418
def rename(self, *args, **kwargs):
419
395
"""Add the new name to the syslog messages"""
420
ret = AvahiService.rename(self, *args, **kwargs)
421
syslogger.setFormatter(logging.Formatter(
422
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
396
ret = AvahiService.rename(self)
397
syslogger.setFormatter(logging.Formatter
398
('Mandos ({}) [%(process)d]:'
399
' %(levelname)s: %(message)s'
473
450
"fingerprint", "host", "interval",
474
451
"last_approval_request", "last_checked_ok",
475
452
"last_enabled", "name", "timeout")
478
"extended_timeout": "PT15M",
480
"checker": "fping -q -- %%(host)s",
482
"approval_delay": "PT0S",
483
"approval_duration": "PT1S",
484
"approved_by_default": "True",
453
client_defaults = { "timeout": "PT5M",
454
"extended_timeout": "PT15M",
456
"checker": "fping -q -- %%(host)s",
458
"approval_delay": "PT0S",
459
"approval_duration": "PT1S",
460
"approved_by_default": "True",
489
465
def config_parser(config):
555
528
self.expires = None
557
530
logger.debug("Creating client %r", self.name)
531
# Uppercase and remove spaces from fingerprint for later
532
# comparison purposes with return value from the fingerprint()
558
534
logger.debug(" Fingerprint: %s", self.fingerprint)
559
535
self.created = settings.get("created",
560
536
datetime.datetime.utcnow())
567
543
self.current_checker_command = None
568
544
self.approved = None
569
545
self.approvals_pending = 0
570
self.changedstate = multiprocessing_manager.Condition(
571
multiprocessing_manager.Lock())
572
self.client_structure = [attr
573
for attr in self.__dict__.iterkeys()
546
self.changedstate = (multiprocessing_manager
547
.Condition(multiprocessing_manager
549
self.client_structure = [attr for attr in
550
self.__dict__.iterkeys()
574
551
if not attr.startswith("_")]
575
552
self.client_structure.append("client_structure")
577
for name, t in inspect.getmembers(
578
type(self), lambda obj: isinstance(obj, property)):
554
for name, t in inspect.getmembers(type(self),
579
558
if not name.startswith("_"):
580
559
self.client_structure.append(name)
623
602
# and every interval from then on.
624
603
if self.checker_initiator_tag is not None:
625
604
gobject.source_remove(self.checker_initiator_tag)
626
self.checker_initiator_tag = gobject.timeout_add(
627
int(self.interval.total_seconds() * 1000),
605
self.checker_initiator_tag = (gobject.timeout_add
607
.total_seconds() * 1000),
629
609
# Schedule a disable() when 'timeout' has passed
630
610
if self.disable_initiator_tag is not None:
631
611
gobject.source_remove(self.disable_initiator_tag)
632
self.disable_initiator_tag = gobject.timeout_add(
633
int(self.timeout.total_seconds() * 1000), self.disable)
612
self.disable_initiator_tag = (gobject.timeout_add
614
.total_seconds() * 1000),
634
616
# Also start a new checker *right now*.
635
617
self.start_checker()
665
648
gobject.source_remove(self.disable_initiator_tag)
666
649
self.disable_initiator_tag = None
667
650
if getattr(self, "enabled", False):
668
self.disable_initiator_tag = gobject.timeout_add(
669
int(timeout.total_seconds() * 1000), self.disable)
651
self.disable_initiator_tag = (gobject.timeout_add
652
(int(timeout.total_seconds()
653
* 1000), self.disable))
670
654
self.expires = datetime.datetime.utcnow() + timeout
672
656
def need_approval(self):
703
687
# Start a new checker if needed
704
688
if self.checker is None:
705
689
# Escape attributes for the shell
707
attr: re.escape(str(getattr(self, attr)))
708
for attr in self.runtime_expansions }
690
escaped_attrs = { attr:
691
re.escape(str(getattr(self, attr)))
692
for attr in self.runtime_expansions }
710
694
command = self.checker_command % escaped_attrs
711
695
except TypeError as error:
712
696
logger.error('Could not format string "%s"',
713
self.checker_command,
715
return True # Try again later
697
self.checker_command, exc_info=error)
698
return True # Try again later
716
699
self.current_checker_command = command
718
logger.info("Starting checker %r for %s", command,
701
logger.info("Starting checker %r for %s",
720
703
# We don't need to redirect stdout and stderr, since
721
704
# in normal mode, that is already done by daemon(),
722
705
# and in debug mode we don't want to. (Stdin is
731
714
"stderr": wnull })
732
715
self.checker = subprocess.Popen(command,
737
719
except OSError as error:
738
720
logger.error("Failed to start subprocess",
741
self.checker_callback_tag = gobject.child_watch_add(
742
self.checker.pid, self.checker_callback, data=command)
723
self.checker_callback_tag = (gobject.child_watch_add
725
self.checker_callback,
743
727
# The checker may have completed before the gobject
744
728
# watch was added. Check for this.
776
760
self.checker = None
779
def dbus_service_property(dbus_interface,
763
def dbus_service_property(dbus_interface, signature="v",
764
access="readwrite", byte_arrays=False):
783
765
"""Decorators for marking methods of a DBusObjectWithProperties to
784
766
become properties on the D-Bus.
835
813
"""Decorator to annotate D-Bus methods, signals or properties
838
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
839
"org.freedesktop.DBus.Property."
840
"EmitsChangedSignal": "false"})
841
816
@dbus_service_property("org.example.Interface", signature="b",
818
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
819
"org.freedesktop.DBus.Property."
820
"EmitsChangedSignal": "false"})
843
821
def Property_dbus_property(self):
844
822
return dbus.Boolean(False)
847
824
def decorator(func):
848
825
func._dbus_annotations = annotations
890
865
def _get_all_dbus_things(self, thing):
891
866
"""Returns a generator of (name, attribute) pairs
893
return ((getattr(athing.__get__(self), "_dbus_name", name),
868
return ((getattr(athing.__get__(self), "_dbus_name",
894
870
athing.__get__(self))
895
871
for cls in self.__class__.__mro__
896
872
for name, athing in
897
inspect.getmembers(cls, self._is_dbus_thing(thing)))
873
inspect.getmembers(cls,
874
self._is_dbus_thing(thing)))
899
876
def _get_dbus_property(self, interface_name, property_name):
900
877
"""Returns a bound method if one exists which is a D-Bus
901
878
property with the specified name and interface.
903
for cls in self.__class__.__mro__:
904
for name, value in inspect.getmembers(
905
cls, self._is_dbus_thing("property")):
880
for cls in self.__class__.__mro__:
881
for name, value in (inspect.getmembers
883
self._is_dbus_thing("property"))):
906
884
if (value._dbus_name == property_name
907
885
and value._dbus_interface == interface_name):
908
886
return value.__get__(self)
910
888
# No such property
911
raise DBusPropertyNotFound("{}:{}.{}".format(
912
self.dbus_object_path, interface_name, property_name))
889
raise DBusPropertyNotFound(self.dbus_object_path + ":"
890
+ interface_name + "."
914
@dbus.service.method(dbus.PROPERTIES_IFACE,
893
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
916
894
out_signature="v")
917
895
def Get(self, interface_name, property_name):
918
896
"""Standard D-Bus property Get() method, see D-Bus standard.
965
942
if not hasattr(value, "variant_level"):
966
943
properties[name] = value
968
properties[name] = type(value)(
969
value, variant_level = value.variant_level + 1)
945
properties[name] = type(value)(value, variant_level=
946
value.variant_level+1)
970
947
return dbus.Dictionary(properties, signature="sv")
972
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
973
def PropertiesChanged(self, interface_name, changed_properties,
974
invalidated_properties):
975
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
980
949
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
981
950
out_signature="s",
982
951
path_keyword='object_path',
992
961
document = xml.dom.minidom.parseString(xmlstring)
994
962
def make_tag(document, name, prop):
995
963
e = document.createElement("property")
996
964
e.setAttribute("name", name)
997
965
e.setAttribute("type", prop._dbus_signature)
998
966
e.setAttribute("access", prop._dbus_access)
1001
968
for if_tag in document.getElementsByTagName("interface"):
1002
969
# Add property tags
1003
970
for tag in (make_tag(document, name, prop)
1063
1032
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1065
1034
return dbus.String("", variant_level = variant_level)
1066
return dbus.String(dt.isoformat(), variant_level=variant_level)
1035
return dbus.String(dt.isoformat(),
1036
variant_level=variant_level)
1069
1039
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1100
1069
# Ignore non-D-Bus attributes, and D-Bus attributes
1101
1070
# with the wrong interface name
1102
1071
if (not hasattr(attribute, "_dbus_interface")
1103
or not attribute._dbus_interface.startswith(
1104
orig_interface_name)):
1072
or not attribute._dbus_interface
1073
.startswith(orig_interface_name)):
1106
1075
# Create an alternate D-Bus interface name based on
1107
1076
# the current name
1108
alt_interface = attribute._dbus_interface.replace(
1109
orig_interface_name, alt_interface_name)
1077
alt_interface = (attribute._dbus_interface
1078
.replace(orig_interface_name,
1079
alt_interface_name))
1110
1080
interface_names.add(alt_interface)
1111
1081
# Is this a D-Bus signal?
1112
1082
if getattr(attribute, "_dbus_is_signal", False):
1113
1083
# Extract the original non-method undecorated
1114
1084
# function by black magic
1115
1085
nonmethod_func = (dict(
1116
zip(attribute.func_code.co_freevars,
1117
attribute.__closure__))
1118
["func"].cell_contents)
1086
zip(attribute.func_code.co_freevars,
1087
attribute.__closure__))["func"]
1119
1089
# Create a new, but exactly alike, function
1120
1090
# object, and decorate it to be a new D-Bus signal
1121
1091
# with the alternate D-Bus interface name
1122
new_function = (dbus.service.signal(
1123
alt_interface, attribute._dbus_signature)
1092
new_function = (dbus.service.signal
1094
attribute._dbus_signature)
1124
1095
(types.FunctionType(
1125
nonmethod_func.func_code,
1126
nonmethod_func.func_globals,
1127
nonmethod_func.func_name,
1128
nonmethod_func.func_defaults,
1129
nonmethod_func.func_closure)))
1096
nonmethod_func.func_code,
1097
nonmethod_func.func_globals,
1098
nonmethod_func.func_name,
1099
nonmethod_func.func_defaults,
1100
nonmethod_func.func_closure)))
1130
1101
# Copy annotations, if any
1132
new_function._dbus_annotations = dict(
1133
attribute._dbus_annotations)
1103
new_function._dbus_annotations = (
1104
dict(attribute._dbus_annotations))
1134
1105
except AttributeError:
1136
1107
# Define a creator of a function to call both the
1141
1112
"""This function is a scope container to pass
1142
1113
func1 and func2 to the "call_both" function
1143
1114
outside of its arguments"""
1145
1115
def call_both(*args, **kwargs):
1146
1116
"""This function will emit two D-Bus
1147
1117
signals by calling func1 and func2"""
1148
1118
func1(*args, **kwargs)
1149
1119
func2(*args, **kwargs)
1151
1120
return call_both
1152
1121
# Create the "call_both" function and add it to
1158
1127
# object. Decorate it to be a new D-Bus method
1159
1128
# with the alternate D-Bus interface name. Add it
1160
1129
# to the class.
1162
dbus.service.method(
1164
attribute._dbus_in_signature,
1165
attribute._dbus_out_signature)
1166
(types.FunctionType(attribute.func_code,
1167
attribute.func_globals,
1168
attribute.func_name,
1169
attribute.func_defaults,
1170
attribute.func_closure)))
1130
attr[attrname] = (dbus.service.method
1132
attribute._dbus_in_signature,
1133
attribute._dbus_out_signature)
1135
(attribute.func_code,
1136
attribute.func_globals,
1137
attribute.func_name,
1138
attribute.func_defaults,
1139
attribute.func_closure)))
1171
1140
# Copy annotations, if any
1173
attr[attrname]._dbus_annotations = dict(
1174
attribute._dbus_annotations)
1142
attr[attrname]._dbus_annotations = (
1143
dict(attribute._dbus_annotations))
1175
1144
except AttributeError:
1177
1146
# Is this a D-Bus property?
1180
1149
# object, and decorate it to be a new D-Bus
1181
1150
# property with the alternate D-Bus interface
1182
1151
# name. Add it to the class.
1183
attr[attrname] = (dbus_service_property(
1184
alt_interface, attribute._dbus_signature,
1185
attribute._dbus_access,
1186
attribute._dbus_get_args_options
1188
(types.FunctionType(
1189
attribute.func_code,
1190
attribute.func_globals,
1191
attribute.func_name,
1192
attribute.func_defaults,
1193
attribute.func_closure)))
1152
attr[attrname] = (dbus_service_property
1154
attribute._dbus_signature,
1155
attribute._dbus_access,
1157
._dbus_get_args_options
1160
(attribute.func_code,
1161
attribute.func_globals,
1162
attribute.func_name,
1163
attribute.func_defaults,
1164
attribute.func_closure)))
1194
1165
# Copy annotations, if any
1196
attr[attrname]._dbus_annotations = dict(
1197
attribute._dbus_annotations)
1167
attr[attrname]._dbus_annotations = (
1168
dict(attribute._dbus_annotations))
1198
1169
except AttributeError:
1200
1171
# Is this a D-Bus interface?
1203
1174
# object. Decorate it to be a new D-Bus interface
1204
1175
# with the alternate D-Bus interface name. Add it
1205
1176
# to the class.
1207
dbus_interface_annotations(alt_interface)
1208
(types.FunctionType(attribute.func_code,
1209
attribute.func_globals,
1210
attribute.func_name,
1211
attribute.func_defaults,
1212
attribute.func_closure)))
1177
attr[attrname] = (dbus_interface_annotations
1180
(attribute.func_code,
1181
attribute.func_globals,
1182
attribute.func_name,
1183
attribute.func_defaults,
1184
attribute.func_closure)))
1214
1186
# Deprecate all alternate interfaces
1215
1187
iname="_AlternateDBusNames_interface_annotation{}"
1216
1188
for interface_name in interface_names:
1218
1189
@dbus_interface_annotations(interface_name)
1219
1190
def func(self):
1220
1191
return { "org.freedesktop.DBus.Deprecated":
1222
1193
# Find an unused name
1223
1194
for aname in (iname.format(i)
1224
1195
for i in itertools.count()):
1229
1200
# Replace the class with a new subclass of it with
1230
1201
# methods, signals, etc. as created above.
1231
1202
cls = type(b"{}Alternate".format(cls.__name__),
1238
1208
@alternate_dbus_interfaces({"se.recompile.Mandos":
1239
"se.bsnet.fukt.Mandos"})
1209
"se.bsnet.fukt.Mandos"})
1240
1210
class ClientDBus(Client, DBusObjectWithProperties):
1241
1211
"""A Client class using D-Bus
1260
1228
client_object_name = str(self.name).translate(
1261
1229
{ord("."): ord("_"),
1262
1230
ord("-"): ord("_")})
1263
self.dbus_object_path = dbus.ObjectPath(
1264
"/clients/" + client_object_name)
1231
self.dbus_object_path = (dbus.ObjectPath
1232
("/clients/" + client_object_name))
1265
1233
DBusObjectWithProperties.__init__(self, self.bus,
1266
1234
self.dbus_object_path)
1268
def notifychangeproperty(transform_func, dbus_name,
1269
type_func=lambda x: x,
1271
invalidate_only=False,
1272
_interface=_interface):
1236
def notifychangeproperty(transform_func,
1237
dbus_name, type_func=lambda x: x,
1273
1239
""" Modify a variable so that it's a property which announces
1274
1240
its changes to DBus.
1281
1247
variant_level: D-Bus variant level. Default: 1
1283
1249
attrname = "_{}".format(dbus_name)
1285
1250
def setter(self, value):
1286
1251
if hasattr(self, "dbus_object_path"):
1287
1252
if (not hasattr(self, attrname) or
1288
1253
type_func(getattr(self, attrname, None))
1289
1254
!= type_func(value)):
1291
self.PropertiesChanged(
1292
_interface, dbus.Dictionary(),
1293
dbus.Array((dbus_name, )))
1295
dbus_value = transform_func(
1297
variant_level = variant_level)
1298
self.PropertyChanged(dbus.String(dbus_name),
1300
self.PropertiesChanged(
1302
dbus.Dictionary({ dbus.String(dbus_name):
1255
dbus_value = transform_func(type_func(value),
1258
self.PropertyChanged(dbus.String(dbus_name),
1305
1260
setattr(self, attrname, value)
1307
1262
return property(lambda self: getattr(self, attrname), setter)
1313
1268
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1314
1269
last_enabled = notifychangeproperty(datetime_to_dbus,
1316
checker = notifychangeproperty(
1317
dbus.Boolean, "CheckerRunning",
1318
type_func = lambda checker: checker is not None)
1271
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1272
type_func = lambda checker:
1273
checker is not None)
1319
1274
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1320
1275
"LastCheckedOK")
1321
1276
last_checker_status = notifychangeproperty(dbus.Int16,
1324
1279
datetime_to_dbus, "LastApprovalRequest")
1325
1280
approved_by_default = notifychangeproperty(dbus.Boolean,
1326
1281
"ApprovedByDefault")
1327
approval_delay = notifychangeproperty(
1328
dbus.UInt64, "ApprovalDelay",
1329
type_func = lambda td: td.total_seconds() * 1000)
1282
approval_delay = notifychangeproperty(dbus.UInt64,
1285
lambda td: td.total_seconds()
1330
1287
approval_duration = notifychangeproperty(
1331
1288
dbus.UInt64, "ApprovalDuration",
1332
1289
type_func = lambda td: td.total_seconds() * 1000)
1333
1290
host = notifychangeproperty(dbus.String, "Host")
1334
timeout = notifychangeproperty(
1335
dbus.UInt64, "Timeout",
1336
type_func = lambda td: td.total_seconds() * 1000)
1291
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1292
type_func = lambda td:
1293
td.total_seconds() * 1000)
1337
1294
extended_timeout = notifychangeproperty(
1338
1295
dbus.UInt64, "ExtendedTimeout",
1339
1296
type_func = lambda td: td.total_seconds() * 1000)
1340
interval = notifychangeproperty(
1341
dbus.UInt64, "Interval",
1342
type_func = lambda td: td.total_seconds() * 1000)
1297
interval = notifychangeproperty(dbus.UInt64,
1300
lambda td: td.total_seconds()
1343
1302
checker_command = notifychangeproperty(dbus.String, "Checker")
1344
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1345
invalidate_only=True)
1347
1304
del notifychangeproperty
1483
1445
return dbus.Boolean(bool(self.approvals_pending))
1485
1447
# ApprovedByDefault - property
1486
@dbus_service_property(_interface,
1448
@dbus_service_property(_interface, signature="b",
1488
1449
access="readwrite")
1489
1450
def ApprovedByDefault_dbus_property(self, value=None):
1490
1451
if value is None: # get
1492
1453
self.approved_by_default = bool(value)
1494
1455
# ApprovalDelay - property
1495
@dbus_service_property(_interface,
1456
@dbus_service_property(_interface, signature="t",
1497
1457
access="readwrite")
1498
1458
def ApprovalDelay_dbus_property(self, value=None):
1499
1459
if value is None: # get
1502
1462
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1504
1464
# ApprovalDuration - property
1505
@dbus_service_property(_interface,
1465
@dbus_service_property(_interface, signature="t",
1507
1466
access="readwrite")
1508
1467
def ApprovalDuration_dbus_property(self, value=None):
1509
1468
if value is None: # get
1563
1519
return datetime_to_dbus(self.last_checked_ok)
1565
1521
# LastCheckerStatus - property
1566
@dbus_service_property(_interface, signature="n", access="read")
1522
@dbus_service_property(_interface, signature="n",
1567
1524
def LastCheckerStatus_dbus_property(self):
1568
1525
return dbus.Int16(self.last_checker_status)
1600
1556
gobject.source_remove(self.disable_initiator_tag)
1601
self.disable_initiator_tag = gobject.timeout_add(
1602
int((self.expires - now).total_seconds() * 1000),
1557
self.disable_initiator_tag = (
1558
gobject.timeout_add(
1559
int((self.expires - now).total_seconds()
1560
* 1000), self.disable))
1605
1562
# ExtendedTimeout - property
1606
@dbus_service_property(_interface,
1563
@dbus_service_property(_interface, signature="t",
1608
1564
access="readwrite")
1609
1565
def ExtendedTimeout_dbus_property(self, value=None):
1610
1566
if value is None: # get
1613
1569
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1615
1571
# Interval - property
1616
@dbus_service_property(_interface,
1572
@dbus_service_property(_interface, signature="t",
1618
1573
access="readwrite")
1619
1574
def Interval_dbus_property(self, value=None):
1620
1575
if value is None: # get
1625
1580
if self.enabled:
1626
1581
# Reschedule checker run
1627
1582
gobject.source_remove(self.checker_initiator_tag)
1628
self.checker_initiator_tag = gobject.timeout_add(
1629
value, self.start_checker)
1630
self.start_checker() # Start one now, too
1583
self.checker_initiator_tag = (gobject.timeout_add
1584
(value, self.start_checker))
1585
self.start_checker() # Start one now, too
1632
1587
# Checker - property
1633
@dbus_service_property(_interface,
1588
@dbus_service_property(_interface, signature="s",
1635
1589
access="readwrite")
1636
1590
def Checker_dbus_property(self, value=None):
1637
1591
if value is None: # get
1656
1609
return self.dbus_object_path # is already a dbus.ObjectPath
1658
1611
# Secret = property
1659
@dbus_service_property(_interface,
1612
@dbus_service_property(_interface, signature="ay",
1613
access="write", byte_arrays=True)
1663
1614
def Secret_dbus_property(self, value):
1664
1615
self.secret = bytes(value)
1681
1632
if data[0] == 'data':
1683
1634
if data[0] == 'function':
1685
1635
def func(*args, **kwargs):
1686
1636
self._pipe.send(('funcall', name, args, kwargs))
1687
1637
return self._pipe.recv()[1]
1691
1640
def __setattr__(self, name, value):
1707
1656
logger.debug("Pipe FD: %d",
1708
1657
self.server.child_pipe.fileno())
1710
session = gnutls.connection.ClientSession(
1711
self.request, gnutls.connection .X509Credentials())
1659
session = (gnutls.connection
1660
.ClientSession(self.request,
1662
.X509Credentials()))
1713
1664
# Note: gnutls.connection.X509Credentials is really a
1714
1665
# generic GnuTLS certificate credentials object so long as
1723
1674
priority = self.server.gnutls_priority
1724
1675
if priority is None:
1725
1676
priority = "NORMAL"
1726
gnutls.library.functions.gnutls_priority_set_direct(
1727
session._c_object, priority, None)
1677
(gnutls.library.functions
1678
.gnutls_priority_set_direct(session._c_object,
1729
1681
# Start communication using the Mandos protocol
1730
1682
# Get protocol number
1825
1777
logger.warning("gnutls send failed",
1826
1778
exc_info=error)
1828
logger.debug("Sent: %d, remaining: %d", sent,
1829
len(client.secret) - (sent_size
1780
logger.debug("Sent: %d, remaining: %d",
1781
sent, len(client.secret)
1782
- (sent_size + sent))
1831
1783
sent_size += sent
1833
1785
logger.info("Sending secret to %s", client.name)
1850
1802
def peer_certificate(session):
1851
1803
"Return the peer's OpenPGP certificate as a bytestring"
1852
1804
# If not an OpenPGP certificate...
1853
if (gnutls.library.functions.gnutls_certificate_type_get(
1805
if (gnutls.library.functions
1806
.gnutls_certificate_type_get(session._c_object)
1855
1807
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1856
1808
# ...do the normal thing
1857
1809
return session.peer_certificate
1871
1823
def fingerprint(openpgp):
1872
1824
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1873
1825
# New GnuTLS "datum" with the OpenPGP public key
1874
datum = gnutls.library.types.gnutls_datum_t(
1875
ctypes.cast(ctypes.c_char_p(openpgp),
1876
ctypes.POINTER(ctypes.c_ubyte)),
1877
ctypes.c_uint(len(openpgp)))
1826
datum = (gnutls.library.types
1827
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1830
ctypes.c_uint(len(openpgp))))
1878
1831
# New empty GnuTLS certificate
1879
1832
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1880
gnutls.library.functions.gnutls_openpgp_crt_init(
1833
(gnutls.library.functions
1834
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1882
1835
# Import the OpenPGP public key into the certificate
1883
gnutls.library.functions.gnutls_openpgp_crt_import(
1884
crt, ctypes.byref(datum),
1885
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1836
(gnutls.library.functions
1837
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1838
gnutls.library.constants
1839
.GNUTLS_OPENPGP_FMT_RAW))
1886
1840
# Verify the self signature in the key
1887
1841
crtverify = ctypes.c_uint()
1888
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1889
crt, 0, ctypes.byref(crtverify))
1842
(gnutls.library.functions
1843
.gnutls_openpgp_crt_verify_self(crt, 0,
1844
ctypes.byref(crtverify)))
1890
1845
if crtverify.value != 0:
1891
1846
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1892
raise gnutls.errors.CertificateSecurityError(
1847
raise (gnutls.errors.CertificateSecurityError
1894
1849
# New buffer for the fingerprint
1895
1850
buf = ctypes.create_string_buffer(20)
1896
1851
buf_len = ctypes.c_size_t()
1897
1852
# Get the fingerprint from the certificate into the buffer
1898
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1899
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1853
(gnutls.library.functions
1854
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1855
ctypes.byref(buf_len)))
1900
1856
# Deinit the certificate
1901
1857
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1902
1858
# Convert the buffer to a Python bytestring
1953
1907
interface: None or a network interface name (string)
1954
1908
use_ipv6: Boolean; to use IPv6 or not
1957
1910
def __init__(self, server_address, RequestHandlerClass,
1911
interface=None, use_ipv6=True, socketfd=None):
1961
1912
"""If socketfd is set, use that file descriptor instead of
1962
1913
creating a new one with socket.socket().
2004
1955
self.interface)
2007
self.socket.setsockopt(
2008
socket.SOL_SOCKET, SO_BINDTODEVICE,
2009
(self.interface + "\0").encode("utf-8"))
1958
self.socket.setsockopt(socket.SOL_SOCKET,
1960
(self.interface + "\0")
2010
1962
except socket.error as error:
2011
1963
if error.errno == errno.EPERM:
2012
1964
logger.error("No permission to bind to"
2030
1982
self.server_address = (any_address,
2031
1983
self.server_address[1])
2032
1984
elif not self.server_address[1]:
2033
self.server_address = (self.server_address[0], 0)
1985
self.server_address = (self.server_address[0],
2034
1987
# if self.interface:
2035
1988
# self.server_address = (self.server_address[0],
2051
2004
Assumes a gobject.MainLoop event loop.
2054
2006
def __init__(self, server_address, RequestHandlerClass,
2058
gnutls_priority=None,
2007
interface=None, use_ipv6=True, clients=None,
2008
gnutls_priority=None, use_dbus=True, socketfd=None):
2061
2009
self.enabled = False
2062
2010
self.clients = clients
2063
2011
if self.clients is None:
2080
2027
def add_pipe(self, parent_pipe, proc):
2081
2028
# Call "handle_ipc" for both data and EOF events
2082
gobject.io_add_watch(
2083
parent_pipe.fileno(),
2084
gobject.IO_IN | gobject.IO_HUP,
2085
functools.partial(self.handle_ipc,
2086
parent_pipe = parent_pipe,
2029
gobject.io_add_watch(parent_pipe.fileno(),
2030
gobject.IO_IN | gobject.IO_HUP,
2031
functools.partial(self.handle_ipc,
2089
def handle_ipc(self, source, condition,
2092
client_object=None):
2036
def handle_ipc(self, source, condition, parent_pipe=None,
2037
proc = None, client_object=None):
2093
2038
# error, or the other end of multiprocessing.Pipe has closed
2094
2039
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2095
2040
# Wait for other process to exit
2118
2063
parent_pipe.send(False)
2121
gobject.io_add_watch(
2122
parent_pipe.fileno(),
2123
gobject.IO_IN | gobject.IO_HUP,
2124
functools.partial(self.handle_ipc,
2125
parent_pipe = parent_pipe,
2127
client_object = client))
2066
gobject.io_add_watch(parent_pipe.fileno(),
2067
gobject.IO_IN | gobject.IO_HUP,
2068
functools.partial(self.handle_ipc,
2128
2074
parent_pipe.send(True)
2129
2075
# remove the old hook in favor of the new above hook on
2137
2083
parent_pipe.send(('data', getattr(client_object,
2138
2084
funcname)(*args,
2141
2087
if command == 'getattr':
2142
2088
attrname = request[1]
2143
2089
if callable(client_object.__getattribute__(attrname)):
2144
parent_pipe.send(('function', ))
2090
parent_pipe.send(('function',))
2147
'data', client_object.__getattribute__(attrname)))
2092
parent_pipe.send(('data', client_object
2093
.__getattribute__(attrname)))
2149
2095
if command == 'setattr':
2150
2096
attrname = request[1]
2191
2137
"followers")) # Tokens valid after
2193
Token = collections.namedtuple("Token", (
2194
"regexp", # To match token; if "value" is not None, must have
2195
# a "group" containing digits
2196
"value", # datetime.timedelta or None
2197
"followers")) # Tokens valid after this token
2198
2139
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2199
2140
# the "duration" ABNF definition in RFC 3339, Appendix A.
2200
2141
token_end = Token(re.compile(r"$"), None, frozenset())
2201
2142
token_second = Token(re.compile(r"(\d+)S"),
2202
2143
datetime.timedelta(seconds=1),
2203
frozenset((token_end, )))
2144
frozenset((token_end,)))
2204
2145
token_minute = Token(re.compile(r"(\d+)M"),
2205
2146
datetime.timedelta(minutes=1),
2206
2147
frozenset((token_second, token_end)))
2222
2163
frozenset((token_month, token_end)))
2223
2164
token_week = Token(re.compile(r"(\d+)W"),
2224
2165
datetime.timedelta(weeks=1),
2225
frozenset((token_end, )))
2166
frozenset((token_end,)))
2226
2167
token_duration = Token(re.compile(r"P"), None,
2227
2168
frozenset((token_year, token_month,
2228
2169
token_day, token_time,
2318
2260
# Close all standard open file descriptors
2319
2261
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2320
2262
if not stat.S_ISCHR(os.fstat(null).st_mode):
2321
raise OSError(errno.ENODEV,
2322
"{} not a character device"
2263
raise OSError(errno.ENODEV, "{} not a character device"
2323
2264
.format(os.devnull))
2324
2265
os.dup2(null, sys.stdin.fileno())
2325
2266
os.dup2(null, sys.stdout.fileno())
2402
2342
"statedir": "/var/lib/mandos",
2403
2343
"foreground": "False",
2404
2344
"zeroconf": "True",
2407
2347
# Parse config file for server-global settings
2408
2348
server_config = configparser.SafeConfigParser(server_defaults)
2409
2349
del server_defaults
2410
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2350
server_config.read(os.path.join(options.configdir,
2411
2352
# Convert the SafeConfigParser object to a dict
2412
2353
server_settings = server_config.defaults()
2413
2354
# Use the appropriate methods on the non-string config options
2431
2372
# Override the settings from the config file with command line
2432
2373
# options, if set.
2433
2374
for option in ("interface", "address", "port", "debug",
2434
"priority", "servicename", "configdir", "use_dbus",
2435
"use_ipv6", "debuglevel", "restore", "statedir",
2436
"socket", "foreground", "zeroconf"):
2375
"priority", "servicename", "configdir",
2376
"use_dbus", "use_ipv6", "debuglevel", "restore",
2377
"statedir", "socket", "foreground", "zeroconf"):
2437
2378
value = getattr(options, option)
2438
2379
if value is not None:
2439
2380
server_settings[option] = value
2455
2396
##################################################################
2457
if (not server_settings["zeroconf"]
2458
and not (server_settings["port"]
2459
or server_settings["socket"] != "")):
2460
parser.error("Needs port or socket to work without Zeroconf")
2398
if (not server_settings["zeroconf"] and
2399
not (server_settings["port"]
2400
or server_settings["socket"] != "")):
2401
parser.error("Needs port or socket to work without"
2462
2404
# For convenience
2463
2405
debug = server_settings["debug"]
2479
2421
initlogger(debug, level)
2481
2423
if server_settings["servicename"] != "Mandos":
2482
syslogger.setFormatter(
2483
logging.Formatter('Mandos ({}) [%(process)d]:'
2484
' %(levelname)s: %(message)s'.format(
2485
server_settings["servicename"])))
2424
syslogger.setFormatter(logging.Formatter
2425
('Mandos ({}) [%(process)d]:'
2426
' %(levelname)s: %(message)s'
2427
.format(server_settings
2487
2430
# Parse config file with clients
2488
2431
client_config = configparser.SafeConfigParser(Client
2496
2439
socketfd = None
2497
2440
if server_settings["socket"] != "":
2498
2441
socketfd = server_settings["socket"]
2499
tcp_server = MandosServer(
2500
(server_settings["address"], server_settings["port"]),
2502
interface=(server_settings["interface"] or None),
2504
gnutls_priority=server_settings["priority"],
2442
tcp_server = MandosServer((server_settings["address"],
2443
server_settings["port"]),
2445
interface=(server_settings["interface"]
2449
server_settings["priority"],
2507
2452
if not foreground:
2508
2453
pidfilename = "/run/mandos.pid"
2509
2454
if not os.path.isdir("/run/."):
2543
2488
def debug_gnutls(level, string):
2544
2489
logger.debug("GnuTLS: %s", string[:-1])
2546
gnutls.library.functions.gnutls_global_set_log_function(
2491
(gnutls.library.functions
2492
.gnutls_global_set_log_function(debug_gnutls))
2549
2494
# Redirect stdin so all checkers get /dev/null
2550
2495
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2572
2517
bus_name = dbus.service.BusName("se.recompile.Mandos",
2575
old_bus_name = dbus.service.BusName(
2576
"se.bsnet.fukt.Mandos", bus,
2518
bus, do_not_queue=True)
2519
old_bus_name = (dbus.service.BusName
2520
("se.bsnet.fukt.Mandos", bus,
2578
2522
except dbus.exceptions.NameExistsException as e:
2579
2523
logger.error("Disabling D-Bus:", exc_info=e)
2580
2524
use_dbus = False
2582
2526
tcp_server.use_dbus = False
2584
2528
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2585
service = AvahiServiceToSyslog(
2586
name = server_settings["servicename"],
2587
servicetype = "_mandos._tcp",
2588
protocol = protocol,
2529
service = AvahiServiceToSyslog(name =
2530
server_settings["servicename"],
2531
servicetype = "_mandos._tcp",
2532
protocol = protocol, bus = bus)
2590
2533
if server_settings["interface"]:
2591
service.interface = if_nametoindex(
2592
server_settings["interface"].encode("utf-8"))
2534
service.interface = (if_nametoindex
2535
(server_settings["interface"]
2594
2538
global multiprocessing_manager
2595
2539
multiprocessing_manager = multiprocessing.Manager()
2614
2558
if server_settings["restore"]:
2616
2560
with open(stored_state_path, "rb") as stored_state:
2617
clients_data, old_client_settings = pickle.load(
2561
clients_data, old_client_settings = (pickle.load
2619
2563
os.remove(stored_state_path)
2620
2564
except IOError as e:
2621
2565
if e.errno == errno.ENOENT:
2622
logger.warning("Could not load persistent state:"
2623
" {}".format(os.strerror(e.errno)))
2566
logger.warning("Could not load persistent state: {}"
2567
.format(os.strerror(e.errno)))
2625
2569
logger.critical("Could not load persistent state:",
2628
2572
except EOFError as e:
2629
2573
logger.warning("Could not load persistent state: "
2574
"EOFError:", exc_info=e)
2633
2576
with PGPEngine() as pgp:
2634
2577
for client_name, client in clients_data.items():
2663
2606
if not client["last_checked_ok"]:
2664
2607
logger.warning(
2665
2608
"disabling client {} - Client never "
2666
"performed a successful checker".format(
2609
"performed a successful checker"
2610
.format(client_name))
2668
2611
client["enabled"] = False
2669
2612
elif client["last_checker_status"] != 0:
2670
2613
logger.warning(
2671
2614
"disabling client {} - Client last"
2672
" checker failed with error code"
2675
client["last_checker_status"]))
2615
" checker failed with error code {}"
2616
.format(client_name,
2617
client["last_checker_status"]))
2676
2618
client["enabled"] = False
2678
client["expires"] = (
2679
datetime.datetime.utcnow()
2680
+ client["timeout"])
2620
client["expires"] = (datetime.datetime
2622
+ client["timeout"])
2681
2623
logger.debug("Last checker succeeded,"
2682
" keeping {} enabled".format(
2624
" keeping {} enabled"
2625
.format(client_name))
2685
client["secret"] = pgp.decrypt(
2686
client["encrypted_secret"],
2687
client_settings[client_name]["secret"])
2627
client["secret"] = (
2628
pgp.decrypt(client["encrypted_secret"],
2629
client_settings[client_name]
2688
2631
except PGPError:
2689
2632
# If decryption fails, we use secret from new settings
2690
logger.debug("Failed to decrypt {} old secret".format(
2692
client["secret"] = (client_settings[client_name]
2633
logger.debug("Failed to decrypt {} old secret"
2634
.format(client_name))
2635
client["secret"] = (
2636
client_settings[client_name]["secret"])
2695
2638
# Add/remove clients based on new changes made to config
2696
2639
for client_name in (set(old_client_settings)
2703
2646
# Create all client objects
2704
2647
for client_name, client in clients_data.items():
2705
2648
tcp_server.clients[client_name] = client_class(
2649
name = client_name, settings = client,
2708
2650
server_settings = server_settings)
2710
2652
if not tcp_server.clients:
2726
2668
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2730
@alternate_dbus_interfaces(
2731
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2671
@alternate_dbus_interfaces({"se.recompile.Mandos":
2672
"se.bsnet.fukt.Mandos"})
2732
2673
class MandosDBusService(DBusObjectWithProperties):
2733
2674
"""A D-Bus proxy object"""
2735
2675
def __init__(self):
2736
2676
dbus.service.Object.__init__(self, bus, "/")
2738
2677
_interface = "se.recompile.Mandos"
2740
2679
@dbus_interface_annotations(_interface)
2741
2680
def _foo(self):
2743
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2681
return { "org.freedesktop.DBus.Property"
2682
".EmitsChangedSignal":
2746
2685
@dbus.service.signal(_interface, signature="o")
2747
2686
def ClientAdded(self, objpath):
2769
2709
def GetAllClientsWithProperties(self):
2771
2711
return dbus.Dictionary(
2772
{ c.dbus_object_path: c.GetAll("")
2773
for c in tcp_server.clients.itervalues() },
2712
((c.dbus_object_path, c.GetAll(""))
2713
for c in tcp_server.clients.itervalues()),
2774
2714
signature="oa{sv}")
2776
2716
@dbus.service.method(_interface, in_signature="o")
2817
2757
exclude = { "bus", "changedstate", "secret",
2818
2758
"checker", "server_settings" }
2819
for name, typ in inspect.getmembers(dbus.service
2759
for name, typ in (inspect.getmembers
2760
(dbus.service.Object)):
2821
2761
exclude.add(name)
2823
2763
client_dict["encrypted_secret"] = (client
2830
2770
del client_settings[client.name]["secret"]
2833
with tempfile.NamedTemporaryFile(
2837
dir=os.path.dirname(stored_state_path),
2838
delete=False) as stored_state:
2773
with (tempfile.NamedTemporaryFile
2774
(mode='wb', suffix=".pickle", prefix='clients-',
2775
dir=os.path.dirname(stored_state_path),
2776
delete=False)) as stored_state:
2839
2777
pickle.dump((clients, client_settings), stored_state)
2840
tempname = stored_state.name
2778
tempname=stored_state.name
2841
2779
os.rename(tempname, stored_state_path)
2842
2780
except (IOError, OSError) as e: