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
88
88
except ImportError:
89
89
SO_BINDTODEVICE = None
91
if sys.version_info.major == 2:
95
92
stored_state_file = "clients.pickle"
97
94
logger = logging.getLogger()
101
if_nametoindex = ctypes.cdll.LoadLibrary(
102
ctypes.util.find_library("c")).if_nametoindex
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
103
101
except (OSError, AttributeError):
105
102
def if_nametoindex(interface):
106
103
"Get an interface index the hard way, i.e. using fcntl()"
107
104
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
116
113
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler(
120
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
address = "/dev/log"))
116
syslogger = (logging.handlers.SysLogHandler
118
logging.handlers.SysLogHandler.LOG_DAEMON,
119
address = "/dev/log"))
122
120
syslogger.setFormatter(logging.Formatter
123
121
('Mandos [%(process)d]: %(levelname)s:'
187
184
def encrypt(self, data, password):
188
185
passphrase = self.password_encode(password)
189
with tempfile.NamedTemporaryFile(
190
dir=self.tempdir) as passfile:
186
with tempfile.NamedTemporaryFile(dir=self.tempdir
191
188
passfile.write(passphrase)
193
190
proc = subprocess.Popen(['gpg', '--symmetric',
205
202
def decrypt(self, data, password):
206
203
passphrase = self.password_encode(password)
207
with tempfile.NamedTemporaryFile(
208
dir = self.tempdir) as passfile:
204
with tempfile.NamedTemporaryFile(dir = self.tempdir
209
206
passfile.write(passphrase)
211
208
proc = subprocess.Popen(['gpg', '--decrypt',
257
253
bus: dbus.SystemBus()
261
interface = avahi.IF_UNSPEC,
269
protocol = avahi.PROTO_UNSPEC,
256
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
257
servicetype = None, port = None, TXT = None,
258
domain = "", host = "", max_renames = 32768,
259
protocol = avahi.PROTO_UNSPEC, bus = None):
271
260
self.interface = interface
273
262
self.type = servicetype
284
273
self.entry_group_state_changed_match = None
286
def rename(self, remove=True):
287
276
"""Derived from the Avahi example code"""
288
277
if self.rename_count >= self.max_renames:
289
278
logger.critical("No suitable Zeroconf service name found"
290
279
" after %i retries, exiting.",
291
280
self.rename_count)
292
281
raise AvahiServiceError("Too many renames")
294
self.server.GetAlternativeServiceName(self.name))
295
self.rename_count += 1
282
self.name = unicode(self.server
283
.GetAlternativeServiceName(self.name))
296
284
logger.info("Changing Zeroconf service name to %r ...",
302
289
except dbus.exceptions.DBusException as error:
303
if (error.get_dbus_name()
304
== "org.freedesktop.Avahi.CollisionError"):
305
logger.info("Local Zeroconf service name collision.")
306
return self.rename(remove=False)
308
logger.critical("D-Bus Exception", exc_info=error)
290
logger.critical("D-Bus Exception", exc_info=error)
293
self.rename_count += 1
312
295
def remove(self):
313
296
"""Derived from the Avahi example code"""
368
352
def server_state_changed(self, state, error=None):
369
353
"""Derived from the Avahi example code"""
370
354
logger.debug("Avahi server state change: %i", state)
372
avahi.SERVER_INVALID: "Zeroconf server invalid",
373
avahi.SERVER_REGISTERING: None,
374
avahi.SERVER_COLLISION: "Zeroconf server name collision",
375
avahi.SERVER_FAILURE: "Zeroconf server failure",
355
bad_states = { avahi.SERVER_INVALID:
356
"Zeroconf server invalid",
357
avahi.SERVER_REGISTERING: None,
358
avahi.SERVER_COLLISION:
359
"Zeroconf server name collision",
360
avahi.SERVER_FAILURE:
361
"Zeroconf server failure" }
377
362
if state in bad_states:
378
363
if bad_states[state] is not None:
379
364
if error is None:
398
383
follow_name_owner_changes=True),
399
384
avahi.DBUS_INTERFACE_SERVER)
400
385
self.server.connect_to_signal("StateChanged",
401
self.server_state_changed)
386
self.server_state_changed)
402
387
self.server_state_changed(self.server.GetState())
405
390
class AvahiServiceToSyslog(AvahiService):
406
def rename(self, *args, **kwargs):
407
392
"""Add the new name to the syslog messages"""
408
ret = AvahiService.rename(self, *args, **kwargs)
409
syslogger.setFormatter(logging.Formatter(
410
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
393
ret = AvahiService.rename(self)
394
syslogger.setFormatter(logging.Formatter
395
('Mandos ({}) [%(process)d]:'
396
' %(levelname)s: %(message)s'
461
447
"fingerprint", "host", "interval",
462
448
"last_approval_request", "last_checked_ok",
463
449
"last_enabled", "name", "timeout")
466
"extended_timeout": "PT15M",
468
"checker": "fping -q -- %%(host)s",
470
"approval_delay": "PT0S",
471
"approval_duration": "PT1S",
472
"approved_by_default": "True",
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",
477
462
def config_parser(config):
543
525
self.expires = None
545
527
logger.debug("Creating client %r", self.name)
528
# Uppercase and remove spaces from fingerprint for later
529
# comparison purposes with return value from the fingerprint()
546
531
logger.debug(" Fingerprint: %s", self.fingerprint)
547
532
self.created = settings.get("created",
548
533
datetime.datetime.utcnow())
555
540
self.current_checker_command = None
556
541
self.approved = None
557
542
self.approvals_pending = 0
558
self.changedstate = multiprocessing_manager.Condition(
559
multiprocessing_manager.Lock())
560
self.client_structure = [attr
561
for attr in self.__dict__.iterkeys()
543
self.changedstate = (multiprocessing_manager
544
.Condition(multiprocessing_manager
546
self.client_structure = [attr for attr in
547
self.__dict__.iterkeys()
562
548
if not attr.startswith("_")]
563
549
self.client_structure.append("client_structure")
565
for name, t in inspect.getmembers(
566
type(self), lambda obj: isinstance(obj, property)):
551
for name, t in inspect.getmembers(type(self),
567
555
if not name.startswith("_"):
568
556
self.client_structure.append(name)
611
599
# and every interval from then on.
612
600
if self.checker_initiator_tag is not None:
613
601
gobject.source_remove(self.checker_initiator_tag)
614
self.checker_initiator_tag = gobject.timeout_add(
615
int(self.interval.total_seconds() * 1000),
602
self.checker_initiator_tag = (gobject.timeout_add
604
.total_seconds() * 1000),
617
606
# Schedule a disable() when 'timeout' has passed
618
607
if self.disable_initiator_tag is not None:
619
608
gobject.source_remove(self.disable_initiator_tag)
620
self.disable_initiator_tag = gobject.timeout_add(
621
int(self.timeout.total_seconds() * 1000), self.disable)
609
self.disable_initiator_tag = (gobject.timeout_add
611
.total_seconds() * 1000),
622
613
# Also start a new checker *right now*.
623
614
self.start_checker()
653
645
gobject.source_remove(self.disable_initiator_tag)
654
646
self.disable_initiator_tag = None
655
647
if getattr(self, "enabled", False):
656
self.disable_initiator_tag = gobject.timeout_add(
657
int(timeout.total_seconds() * 1000), self.disable)
648
self.disable_initiator_tag = (gobject.timeout_add
649
(int(timeout.total_seconds()
650
* 1000), self.disable))
658
651
self.expires = datetime.datetime.utcnow() + timeout
660
653
def need_approval(self):
691
684
# Start a new checker if needed
692
685
if self.checker is None:
693
686
# Escape attributes for the shell
695
attr: re.escape(str(getattr(self, attr)))
696
for attr in self.runtime_expansions }
687
escaped_attrs = { attr:
688
re.escape(unicode(getattr(self,
690
for attr in self.runtime_expansions }
698
692
command = self.checker_command % escaped_attrs
699
693
except TypeError as error:
700
694
logger.error('Could not format string "%s"',
701
self.checker_command,
703
return True # Try again later
695
self.checker_command, exc_info=error)
696
return True # Try again later
704
697
self.current_checker_command = command
706
logger.info("Starting checker %r for %s", command,
699
logger.info("Starting checker %r for %s",
708
701
# We don't need to redirect stdout and stderr, since
709
702
# in normal mode, that is already done by daemon(),
710
703
# and in debug mode we don't want to. (Stdin is
719
712
"stderr": wnull })
720
713
self.checker = subprocess.Popen(command,
725
717
except OSError as error:
726
718
logger.error("Failed to start subprocess",
729
self.checker_callback_tag = gobject.child_watch_add(
730
self.checker.pid, self.checker_callback, data=command)
721
self.checker_callback_tag = (gobject.child_watch_add
723
self.checker_callback,
731
725
# The checker may have completed before the gobject
732
726
# watch was added. Check for this.
764
758
self.checker = None
767
def dbus_service_property(dbus_interface,
761
def dbus_service_property(dbus_interface, signature="v",
762
access="readwrite", byte_arrays=False):
771
763
"""Decorators for marking methods of a DBusObjectWithProperties to
772
764
become properties on the D-Bus.
823
811
"""Decorator to annotate D-Bus methods, signals or properties
826
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
827
"org.freedesktop.DBus.Property."
828
"EmitsChangedSignal": "false"})
829
814
@dbus_service_property("org.example.Interface", signature="b",
816
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
817
"org.freedesktop.DBus.Property."
818
"EmitsChangedSignal": "false"})
831
819
def Property_dbus_property(self):
832
820
return dbus.Boolean(False)
835
822
def decorator(func):
836
823
func._dbus_annotations = annotations
878
863
def _get_all_dbus_things(self, thing):
879
864
"""Returns a generator of (name, attribute) pairs
881
return ((getattr(athing.__get__(self), "_dbus_name", name),
866
return ((getattr(athing.__get__(self), "_dbus_name",
882
868
athing.__get__(self))
883
869
for cls in self.__class__.__mro__
884
870
for name, athing in
885
inspect.getmembers(cls, self._is_dbus_thing(thing)))
871
inspect.getmembers(cls,
872
self._is_dbus_thing(thing)))
887
874
def _get_dbus_property(self, interface_name, property_name):
888
875
"""Returns a bound method if one exists which is a D-Bus
889
876
property with the specified name and interface.
891
for cls in self.__class__.__mro__:
892
for name, value in inspect.getmembers(
893
cls, self._is_dbus_thing("property")):
878
for cls in self.__class__.__mro__:
879
for name, value in (inspect.getmembers
881
self._is_dbus_thing("property"))):
894
882
if (value._dbus_name == property_name
895
883
and value._dbus_interface == interface_name):
896
884
return value.__get__(self)
898
886
# No such property
899
raise DBusPropertyNotFound("{}:{}.{}".format(
900
self.dbus_object_path, interface_name, property_name))
887
raise DBusPropertyNotFound(self.dbus_object_path + ":"
888
+ interface_name + "."
902
@dbus.service.method(dbus.PROPERTIES_IFACE,
891
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
892
out_signature="v")
905
893
def Get(self, interface_name, property_name):
906
894
"""Standard D-Bus property Get() method, see D-Bus standard.
953
940
if not hasattr(value, "variant_level"):
954
941
properties[name] = value
956
properties[name] = type(value)(
957
value, variant_level = value.variant_level + 1)
943
properties[name] = type(value)(value, variant_level=
944
value.variant_level+1)
958
945
return dbus.Dictionary(properties, signature="sv")
960
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
961
def PropertiesChanged(self, interface_name, changed_properties,
962
invalidated_properties):
963
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
968
947
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
969
948
out_signature="s",
970
949
path_keyword='object_path',
980
959
document = xml.dom.minidom.parseString(xmlstring)
982
960
def make_tag(document, name, prop):
983
961
e = document.createElement("property")
984
962
e.setAttribute("name", name)
985
963
e.setAttribute("type", prop._dbus_signature)
986
964
e.setAttribute("access", prop._dbus_access)
989
966
for if_tag in document.getElementsByTagName("interface"):
990
967
# Add property tags
991
968
for tag in (make_tag(document, name, prop)
1051
1030
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1053
1032
return dbus.String("", variant_level = variant_level)
1054
return dbus.String(dt.isoformat(), variant_level=variant_level)
1033
return dbus.String(dt.isoformat(),
1034
variant_level=variant_level)
1057
1037
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1088
1067
# Ignore non-D-Bus attributes, and D-Bus attributes
1089
1068
# with the wrong interface name
1090
1069
if (not hasattr(attribute, "_dbus_interface")
1091
or not attribute._dbus_interface.startswith(
1092
orig_interface_name)):
1070
or not attribute._dbus_interface
1071
.startswith(orig_interface_name)):
1094
1073
# Create an alternate D-Bus interface name based on
1095
1074
# the current name
1096
alt_interface = attribute._dbus_interface.replace(
1097
orig_interface_name, alt_interface_name)
1075
alt_interface = (attribute._dbus_interface
1076
.replace(orig_interface_name,
1077
alt_interface_name))
1098
1078
interface_names.add(alt_interface)
1099
1079
# Is this a D-Bus signal?
1100
1080
if getattr(attribute, "_dbus_is_signal", False):
1101
1081
# Extract the original non-method undecorated
1102
1082
# function by black magic
1103
1083
nonmethod_func = (dict(
1104
zip(attribute.func_code.co_freevars,
1105
attribute.__closure__))
1106
["func"].cell_contents)
1084
zip(attribute.func_code.co_freevars,
1085
attribute.__closure__))["func"]
1107
1087
# Create a new, but exactly alike, function
1108
1088
# object, and decorate it to be a new D-Bus signal
1109
1089
# with the alternate D-Bus interface name
1110
new_function = (dbus.service.signal(
1111
alt_interface, attribute._dbus_signature)
1090
new_function = (dbus.service.signal
1092
attribute._dbus_signature)
1112
1093
(types.FunctionType(
1113
nonmethod_func.func_code,
1114
nonmethod_func.func_globals,
1115
nonmethod_func.func_name,
1116
nonmethod_func.func_defaults,
1117
nonmethod_func.func_closure)))
1094
nonmethod_func.func_code,
1095
nonmethod_func.func_globals,
1096
nonmethod_func.func_name,
1097
nonmethod_func.func_defaults,
1098
nonmethod_func.func_closure)))
1118
1099
# Copy annotations, if any
1120
new_function._dbus_annotations = dict(
1121
attribute._dbus_annotations)
1101
new_function._dbus_annotations = (
1102
dict(attribute._dbus_annotations))
1122
1103
except AttributeError:
1124
1105
# Define a creator of a function to call both the
1129
1110
"""This function is a scope container to pass
1130
1111
func1 and func2 to the "call_both" function
1131
1112
outside of its arguments"""
1133
1113
def call_both(*args, **kwargs):
1134
1114
"""This function will emit two D-Bus
1135
1115
signals by calling func1 and func2"""
1136
1116
func1(*args, **kwargs)
1137
1117
func2(*args, **kwargs)
1139
1118
return call_both
1140
1119
# Create the "call_both" function and add it to
1146
1125
# object. Decorate it to be a new D-Bus method
1147
1126
# with the alternate D-Bus interface name. Add it
1148
1127
# to the class.
1150
dbus.service.method(
1152
attribute._dbus_in_signature,
1153
attribute._dbus_out_signature)
1154
(types.FunctionType(attribute.func_code,
1155
attribute.func_globals,
1156
attribute.func_name,
1157
attribute.func_defaults,
1158
attribute.func_closure)))
1128
attr[attrname] = (dbus.service.method
1130
attribute._dbus_in_signature,
1131
attribute._dbus_out_signature)
1133
(attribute.func_code,
1134
attribute.func_globals,
1135
attribute.func_name,
1136
attribute.func_defaults,
1137
attribute.func_closure)))
1159
1138
# Copy annotations, if any
1161
attr[attrname]._dbus_annotations = dict(
1162
attribute._dbus_annotations)
1140
attr[attrname]._dbus_annotations = (
1141
dict(attribute._dbus_annotations))
1163
1142
except AttributeError:
1165
1144
# Is this a D-Bus property?
1168
1147
# object, and decorate it to be a new D-Bus
1169
1148
# property with the alternate D-Bus interface
1170
1149
# name. Add it to the class.
1171
attr[attrname] = (dbus_service_property(
1172
alt_interface, attribute._dbus_signature,
1173
attribute._dbus_access,
1174
attribute._dbus_get_args_options
1176
(types.FunctionType(
1177
attribute.func_code,
1178
attribute.func_globals,
1179
attribute.func_name,
1180
attribute.func_defaults,
1181
attribute.func_closure)))
1150
attr[attrname] = (dbus_service_property
1152
attribute._dbus_signature,
1153
attribute._dbus_access,
1155
._dbus_get_args_options
1158
(attribute.func_code,
1159
attribute.func_globals,
1160
attribute.func_name,
1161
attribute.func_defaults,
1162
attribute.func_closure)))
1182
1163
# Copy annotations, if any
1184
attr[attrname]._dbus_annotations = dict(
1185
attribute._dbus_annotations)
1165
attr[attrname]._dbus_annotations = (
1166
dict(attribute._dbus_annotations))
1186
1167
except AttributeError:
1188
1169
# Is this a D-Bus interface?
1191
1172
# object. Decorate it to be a new D-Bus interface
1192
1173
# with the alternate D-Bus interface name. Add it
1193
1174
# to the class.
1195
dbus_interface_annotations(alt_interface)
1196
(types.FunctionType(attribute.func_code,
1197
attribute.func_globals,
1198
attribute.func_name,
1199
attribute.func_defaults,
1200
attribute.func_closure)))
1175
attr[attrname] = (dbus_interface_annotations
1178
(attribute.func_code,
1179
attribute.func_globals,
1180
attribute.func_name,
1181
attribute.func_defaults,
1182
attribute.func_closure)))
1202
1184
# Deprecate all alternate interfaces
1203
1185
iname="_AlternateDBusNames_interface_annotation{}"
1204
1186
for interface_name in interface_names:
1206
1187
@dbus_interface_annotations(interface_name)
1207
1188
def func(self):
1208
1189
return { "org.freedesktop.DBus.Deprecated":
1210
1191
# Find an unused name
1211
1192
for aname in (iname.format(i)
1212
1193
for i in itertools.count()):
1217
1198
# Replace the class with a new subclass of it with
1218
1199
# methods, signals, etc. as created above.
1219
1200
cls = type(b"{}Alternate".format(cls.__name__),
1226
1206
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
"se.bsnet.fukt.Mandos"})
1207
"se.bsnet.fukt.Mandos"})
1228
1208
class ClientDBus(Client, DBusObjectWithProperties):
1229
1209
"""A Client class using D-Bus
1245
1223
Client.__init__(self, *args, **kwargs)
1246
1224
# Only now, when this client is initialized, can it show up on
1248
client_object_name = str(self.name).translate(
1226
client_object_name = unicode(self.name).translate(
1249
1227
{ord("."): ord("_"),
1250
1228
ord("-"): ord("_")})
1251
self.dbus_object_path = dbus.ObjectPath(
1252
"/clients/" + client_object_name)
1229
self.dbus_object_path = (dbus.ObjectPath
1230
("/clients/" + client_object_name))
1253
1231
DBusObjectWithProperties.__init__(self, self.bus,
1254
1232
self.dbus_object_path)
1256
def notifychangeproperty(transform_func, dbus_name,
1257
type_func=lambda x: x,
1259
invalidate_only=False,
1260
_interface=_interface):
1234
def notifychangeproperty(transform_func,
1235
dbus_name, type_func=lambda x: x,
1261
1237
""" Modify a variable so that it's a property which announces
1262
1238
its changes to DBus.
1269
1245
variant_level: D-Bus variant level. Default: 1
1271
1247
attrname = "_{}".format(dbus_name)
1273
1248
def setter(self, value):
1274
1249
if hasattr(self, "dbus_object_path"):
1275
1250
if (not hasattr(self, attrname) or
1276
1251
type_func(getattr(self, attrname, None))
1277
1252
!= type_func(value)):
1279
self.PropertiesChanged(
1280
_interface, dbus.Dictionary(),
1281
dbus.Array((dbus_name, )))
1283
dbus_value = transform_func(
1285
variant_level = variant_level)
1286
self.PropertyChanged(dbus.String(dbus_name),
1288
self.PropertiesChanged(
1290
dbus.Dictionary({ dbus.String(dbus_name):
1253
dbus_value = transform_func(type_func(value),
1256
self.PropertyChanged(dbus.String(dbus_name),
1293
1258
setattr(self, attrname, value)
1295
1260
return property(lambda self: getattr(self, attrname), setter)
1301
1266
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1267
last_enabled = notifychangeproperty(datetime_to_dbus,
1304
checker = notifychangeproperty(
1305
dbus.Boolean, "CheckerRunning",
1306
type_func = lambda checker: checker is not None)
1269
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1270
type_func = lambda checker:
1271
checker is not None)
1307
1272
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1273
"LastCheckedOK")
1309
1274
last_checker_status = notifychangeproperty(dbus.Int16,
1312
1277
datetime_to_dbus, "LastApprovalRequest")
1313
1278
approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1279
"ApprovedByDefault")
1315
approval_delay = notifychangeproperty(
1316
dbus.UInt64, "ApprovalDelay",
1317
type_func = lambda td: td.total_seconds() * 1000)
1280
approval_delay = notifychangeproperty(dbus.UInt64,
1283
lambda td: td.total_seconds()
1318
1285
approval_duration = notifychangeproperty(
1319
1286
dbus.UInt64, "ApprovalDuration",
1320
1287
type_func = lambda td: td.total_seconds() * 1000)
1321
1288
host = notifychangeproperty(dbus.String, "Host")
1322
timeout = notifychangeproperty(
1323
dbus.UInt64, "Timeout",
1324
type_func = lambda td: td.total_seconds() * 1000)
1289
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1290
type_func = lambda td:
1291
td.total_seconds() * 1000)
1325
1292
extended_timeout = notifychangeproperty(
1326
1293
dbus.UInt64, "ExtendedTimeout",
1327
1294
type_func = lambda td: td.total_seconds() * 1000)
1328
interval = notifychangeproperty(
1329
dbus.UInt64, "Interval",
1330
type_func = lambda td: td.total_seconds() * 1000)
1295
interval = notifychangeproperty(dbus.UInt64,
1298
lambda td: td.total_seconds()
1331
1300
checker_command = notifychangeproperty(dbus.String, "Checker")
1332
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
invalidate_only=True)
1335
1302
del notifychangeproperty
1471
1443
return dbus.Boolean(bool(self.approvals_pending))
1473
1445
# ApprovedByDefault - property
1474
@dbus_service_property(_interface,
1446
@dbus_service_property(_interface, signature="b",
1476
1447
access="readwrite")
1477
1448
def ApprovedByDefault_dbus_property(self, value=None):
1478
1449
if value is None: # get
1480
1451
self.approved_by_default = bool(value)
1482
1453
# ApprovalDelay - property
1483
@dbus_service_property(_interface,
1454
@dbus_service_property(_interface, signature="t",
1485
1455
access="readwrite")
1486
1456
def ApprovalDelay_dbus_property(self, value=None):
1487
1457
if value is None: # get
1490
1460
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1492
1462
# ApprovalDuration - property
1493
@dbus_service_property(_interface,
1463
@dbus_service_property(_interface, signature="t",
1495
1464
access="readwrite")
1496
1465
def ApprovalDuration_dbus_property(self, value=None):
1497
1466
if value is None: # get
1510
1479
return dbus.String(self.fingerprint)
1512
1481
# Host - property
1513
@dbus_service_property(_interface,
1482
@dbus_service_property(_interface, signature="s",
1515
1483
access="readwrite")
1516
1484
def Host_dbus_property(self, value=None):
1517
1485
if value is None: # get
1518
1486
return dbus.String(self.host)
1519
self.host = str(value)
1487
self.host = unicode(value)
1521
1489
# Created - property
1522
1490
@dbus_service_property(_interface, signature="s", access="read")
1551
1517
return datetime_to_dbus(self.last_checked_ok)
1553
1519
# LastCheckerStatus - property
1554
@dbus_service_property(_interface, signature="n", access="read")
1520
@dbus_service_property(_interface, signature="n",
1555
1522
def LastCheckerStatus_dbus_property(self):
1556
1523
return dbus.Int16(self.last_checker_status)
1588
1554
gobject.source_remove(self.disable_initiator_tag)
1589
self.disable_initiator_tag = gobject.timeout_add(
1590
int((self.expires - now).total_seconds() * 1000),
1555
self.disable_initiator_tag = (
1556
gobject.timeout_add(
1557
int((self.expires - now).total_seconds()
1558
* 1000), self.disable))
1593
1560
# ExtendedTimeout - property
1594
@dbus_service_property(_interface,
1561
@dbus_service_property(_interface, signature="t",
1596
1562
access="readwrite")
1597
1563
def ExtendedTimeout_dbus_property(self, value=None):
1598
1564
if value is None: # get
1601
1567
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1603
1569
# Interval - property
1604
@dbus_service_property(_interface,
1570
@dbus_service_property(_interface, signature="t",
1606
1571
access="readwrite")
1607
1572
def Interval_dbus_property(self, value=None):
1608
1573
if value is None: # get
1613
1578
if self.enabled:
1614
1579
# Reschedule checker run
1615
1580
gobject.source_remove(self.checker_initiator_tag)
1616
self.checker_initiator_tag = gobject.timeout_add(
1617
value, self.start_checker)
1618
self.start_checker() # Start one now, too
1581
self.checker_initiator_tag = (gobject.timeout_add
1582
(value, self.start_checker))
1583
self.start_checker() # Start one now, too
1620
1585
# Checker - property
1621
@dbus_service_property(_interface,
1586
@dbus_service_property(_interface, signature="s",
1623
1587
access="readwrite")
1624
1588
def Checker_dbus_property(self, value=None):
1625
1589
if value is None: # get
1626
1590
return dbus.String(self.checker_command)
1627
self.checker_command = str(value)
1591
self.checker_command = unicode(value)
1629
1593
# CheckerRunning - property
1630
@dbus_service_property(_interface,
1594
@dbus_service_property(_interface, signature="b",
1632
1595
access="readwrite")
1633
1596
def CheckerRunning_dbus_property(self, value=None):
1634
1597
if value is None: # get
1644
1607
return self.dbus_object_path # is already a dbus.ObjectPath
1646
1609
# Secret = property
1647
@dbus_service_property(_interface,
1610
@dbus_service_property(_interface, signature="ay",
1611
access="write", byte_arrays=True)
1651
1612
def Secret_dbus_property(self, value):
1652
1613
self.secret = bytes(value)
1669
1630
if data[0] == 'data':
1671
1632
if data[0] == 'function':
1673
1633
def func(*args, **kwargs):
1674
1634
self._pipe.send(('funcall', name, args, kwargs))
1675
1635
return self._pipe.recv()[1]
1679
1638
def __setattr__(self, name, value):
1691
1650
def handle(self):
1692
1651
with contextlib.closing(self.server.child_pipe) as child_pipe:
1693
1652
logger.info("TCP connection from: %s",
1694
str(self.client_address))
1653
unicode(self.client_address))
1695
1654
logger.debug("Pipe FD: %d",
1696
1655
self.server.child_pipe.fileno())
1698
session = gnutls.connection.ClientSession(
1699
self.request, gnutls.connection .X509Credentials())
1657
session = (gnutls.connection
1658
.ClientSession(self.request,
1660
.X509Credentials()))
1701
1662
# Note: gnutls.connection.X509Credentials is really a
1702
1663
# generic GnuTLS certificate credentials object so long as
1711
1672
priority = self.server.gnutls_priority
1712
1673
if priority is None:
1713
1674
priority = "NORMAL"
1714
gnutls.library.functions.gnutls_priority_set_direct(
1715
session._c_object, priority, None)
1675
(gnutls.library.functions
1676
.gnutls_priority_set_direct(session._c_object,
1717
1679
# Start communication using the Mandos protocol
1718
1680
# Get protocol number
1813
1775
logger.warning("gnutls send failed",
1814
1776
exc_info=error)
1816
logger.debug("Sent: %d, remaining: %d", sent,
1817
len(client.secret) - (sent_size
1778
logger.debug("Sent: %d, remaining: %d",
1779
sent, len(client.secret)
1780
- (sent_size + sent))
1819
1781
sent_size += sent
1821
1783
logger.info("Sending secret to %s", client.name)
1838
1800
def peer_certificate(session):
1839
1801
"Return the peer's OpenPGP certificate as a bytestring"
1840
1802
# If not an OpenPGP certificate...
1841
if (gnutls.library.functions.gnutls_certificate_type_get(
1803
if (gnutls.library.functions
1804
.gnutls_certificate_type_get(session._c_object)
1843
1805
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1806
# ...do the normal thing
1845
1807
return session.peer_certificate
1859
1821
def fingerprint(openpgp):
1860
1822
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1823
# New GnuTLS "datum" with the OpenPGP public key
1862
datum = gnutls.library.types.gnutls_datum_t(
1863
ctypes.cast(ctypes.c_char_p(openpgp),
1864
ctypes.POINTER(ctypes.c_ubyte)),
1865
ctypes.c_uint(len(openpgp)))
1824
datum = (gnutls.library.types
1825
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1828
ctypes.c_uint(len(openpgp))))
1866
1829
# New empty GnuTLS certificate
1867
1830
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
gnutls.library.functions.gnutls_openpgp_crt_init(
1831
(gnutls.library.functions
1832
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1833
# Import the OpenPGP public key into the certificate
1871
gnutls.library.functions.gnutls_openpgp_crt_import(
1872
crt, ctypes.byref(datum),
1873
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1834
(gnutls.library.functions
1835
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1836
gnutls.library.constants
1837
.GNUTLS_OPENPGP_FMT_RAW))
1874
1838
# Verify the self signature in the key
1875
1839
crtverify = ctypes.c_uint()
1876
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
crt, 0, ctypes.byref(crtverify))
1840
(gnutls.library.functions
1841
.gnutls_openpgp_crt_verify_self(crt, 0,
1842
ctypes.byref(crtverify)))
1878
1843
if crtverify.value != 0:
1879
1844
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
raise gnutls.errors.CertificateSecurityError(
1845
raise (gnutls.errors.CertificateSecurityError
1882
1847
# New buffer for the fingerprint
1883
1848
buf = ctypes.create_string_buffer(20)
1884
1849
buf_len = ctypes.c_size_t()
1885
1850
# Get the fingerprint from the certificate into the buffer
1886
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1851
(gnutls.library.functions
1852
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1853
ctypes.byref(buf_len)))
1888
1854
# Deinit the certificate
1889
1855
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1856
# Convert the buffer to a Python bytestring
1941
1905
interface: None or a network interface name (string)
1942
1906
use_ipv6: Boolean; to use IPv6 or not
1945
1908
def __init__(self, server_address, RequestHandlerClass,
1909
interface=None, use_ipv6=True, socketfd=None):
1949
1910
"""If socketfd is set, use that file descriptor instead of
1950
1911
creating a new one with socket.socket().
1992
1953
self.interface)
1995
self.socket.setsockopt(
1996
socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
(self.interface + "\0").encode("utf-8"))
1956
self.socket.setsockopt(socket.SOL_SOCKET,
1958
(self.interface + "\0")
1998
1960
except socket.error as error:
1999
1961
if error.errno == errno.EPERM:
2000
1962
logger.error("No permission to bind to"
2018
1980
self.server_address = (any_address,
2019
1981
self.server_address[1])
2020
1982
elif not self.server_address[1]:
2021
self.server_address = (self.server_address[0], 0)
1983
self.server_address = (self.server_address[0],
2022
1985
# if self.interface:
2023
1986
# self.server_address = (self.server_address[0],
2039
2002
Assumes a gobject.MainLoop event loop.
2042
2004
def __init__(self, server_address, RequestHandlerClass,
2046
gnutls_priority=None,
2005
interface=None, use_ipv6=True, clients=None,
2006
gnutls_priority=None, use_dbus=True, socketfd=None):
2049
2007
self.enabled = False
2050
2008
self.clients = clients
2051
2009
if self.clients is None:
2068
2025
def add_pipe(self, parent_pipe, proc):
2069
2026
# Call "handle_ipc" for both data and EOF events
2070
gobject.io_add_watch(
2071
parent_pipe.fileno(),
2072
gobject.IO_IN | gobject.IO_HUP,
2073
functools.partial(self.handle_ipc,
2074
parent_pipe = parent_pipe,
2027
gobject.io_add_watch(parent_pipe.fileno(),
2028
gobject.IO_IN | gobject.IO_HUP,
2029
functools.partial(self.handle_ipc,
2077
def handle_ipc(self, source, condition,
2080
client_object=None):
2034
def handle_ipc(self, source, condition, parent_pipe=None,
2035
proc = None, client_object=None):
2081
2036
# error, or the other end of multiprocessing.Pipe has closed
2082
2037
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2038
# Wait for other process to exit
2106
2061
parent_pipe.send(False)
2109
gobject.io_add_watch(
2110
parent_pipe.fileno(),
2111
gobject.IO_IN | gobject.IO_HUP,
2112
functools.partial(self.handle_ipc,
2113
parent_pipe = parent_pipe,
2115
client_object = client))
2064
gobject.io_add_watch(parent_pipe.fileno(),
2065
gobject.IO_IN | gobject.IO_HUP,
2066
functools.partial(self.handle_ipc,
2116
2072
parent_pipe.send(True)
2117
2073
# remove the old hook in favor of the new above hook on
2125
2081
parent_pipe.send(('data', getattr(client_object,
2126
2082
funcname)(*args,
2129
2085
if command == 'getattr':
2130
2086
attrname = request[1]
2131
2087
if callable(client_object.__getattribute__(attrname)):
2132
parent_pipe.send(('function', ))
2088
parent_pipe.send(('function',))
2135
'data', client_object.__getattribute__(attrname)))
2090
parent_pipe.send(('data', client_object
2091
.__getattribute__(attrname)))
2137
2093
if command == 'setattr':
2138
2094
attrname = request[1]
2179
2135
"followers")) # Tokens valid after
2181
Token = collections.namedtuple("Token", (
2182
"regexp", # To match token; if "value" is not None, must have
2183
# a "group" containing digits
2184
"value", # datetime.timedelta or None
2185
"followers")) # Tokens valid after this token
2186
2137
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
2138
# the "duration" ABNF definition in RFC 3339, Appendix A.
2188
2139
token_end = Token(re.compile(r"$"), None, frozenset())
2189
2140
token_second = Token(re.compile(r"(\d+)S"),
2190
2141
datetime.timedelta(seconds=1),
2191
frozenset((token_end, )))
2142
frozenset((token_end,)))
2192
2143
token_minute = Token(re.compile(r"(\d+)M"),
2193
2144
datetime.timedelta(minutes=1),
2194
2145
frozenset((token_second, token_end)))
2210
2161
frozenset((token_month, token_end)))
2211
2162
token_week = Token(re.compile(r"(\d+)W"),
2212
2163
datetime.timedelta(weeks=1),
2213
frozenset((token_end, )))
2164
frozenset((token_end,)))
2214
2165
token_duration = Token(re.compile(r"P"), None,
2215
2166
frozenset((token_year, token_month,
2216
2167
token_day, token_time,
2306
2258
# Close all standard open file descriptors
2307
2259
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2260
if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
raise OSError(errno.ENODEV,
2310
"{} not a character device"
2261
raise OSError(errno.ENODEV, "{} not a character device"
2311
2262
.format(os.devnull))
2312
2263
os.dup2(null, sys.stdin.fileno())
2313
2264
os.dup2(null, sys.stdout.fileno())
2390
2340
"statedir": "/var/lib/mandos",
2391
2341
"foreground": "False",
2392
2342
"zeroconf": "True",
2395
2345
# Parse config file for server-global settings
2396
2346
server_config = configparser.SafeConfigParser(server_defaults)
2397
2347
del server_defaults
2398
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2348
server_config.read(os.path.join(options.configdir,
2399
2350
# Convert the SafeConfigParser object to a dict
2400
2351
server_settings = server_config.defaults()
2401
2352
# Use the appropriate methods on the non-string config options
2419
2370
# Override the settings from the config file with command line
2420
2371
# options, if set.
2421
2372
for option in ("interface", "address", "port", "debug",
2422
"priority", "servicename", "configdir", "use_dbus",
2423
"use_ipv6", "debuglevel", "restore", "statedir",
2424
"socket", "foreground", "zeroconf"):
2373
"priority", "servicename", "configdir",
2374
"use_dbus", "use_ipv6", "debuglevel", "restore",
2375
"statedir", "socket", "foreground", "zeroconf"):
2425
2376
value = getattr(options, option)
2426
2377
if value is not None:
2427
2378
server_settings[option] = value
2443
2394
##################################################################
2445
if (not server_settings["zeroconf"]
2446
and not (server_settings["port"]
2447
or server_settings["socket"] != "")):
2448
parser.error("Needs port or socket to work without Zeroconf")
2396
if (not server_settings["zeroconf"] and
2397
not (server_settings["port"]
2398
or server_settings["socket"] != "")):
2399
parser.error("Needs port or socket to work without"
2450
2402
# For convenience
2451
2403
debug = server_settings["debug"]
2467
2419
initlogger(debug, level)
2469
2421
if server_settings["servicename"] != "Mandos":
2470
syslogger.setFormatter(
2471
logging.Formatter('Mandos ({}) [%(process)d]:'
2472
' %(levelname)s: %(message)s'.format(
2473
server_settings["servicename"])))
2422
syslogger.setFormatter(logging.Formatter
2423
('Mandos ({}) [%(process)d]:'
2424
' %(levelname)s: %(message)s'
2425
.format(server_settings
2475
2428
# Parse config file with clients
2476
2429
client_config = configparser.SafeConfigParser(Client
2484
2437
socketfd = None
2485
2438
if server_settings["socket"] != "":
2486
2439
socketfd = server_settings["socket"]
2487
tcp_server = MandosServer(
2488
(server_settings["address"], server_settings["port"]),
2490
interface=(server_settings["interface"] or None),
2492
gnutls_priority=server_settings["priority"],
2440
tcp_server = MandosServer((server_settings["address"],
2441
server_settings["port"]),
2443
interface=(server_settings["interface"]
2447
server_settings["priority"],
2495
2450
if not foreground:
2496
2451
pidfilename = "/run/mandos.pid"
2497
2452
if not os.path.isdir("/run/."):
2531
2486
def debug_gnutls(level, string):
2532
2487
logger.debug("GnuTLS: %s", string[:-1])
2534
gnutls.library.functions.gnutls_global_set_log_function(
2489
(gnutls.library.functions
2490
.gnutls_global_set_log_function(debug_gnutls))
2537
2492
# Redirect stdin so all checkers get /dev/null
2538
2493
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2560
2515
bus_name = dbus.service.BusName("se.recompile.Mandos",
2563
old_bus_name = dbus.service.BusName(
2564
"se.bsnet.fukt.Mandos", bus,
2516
bus, do_not_queue=True)
2517
old_bus_name = (dbus.service.BusName
2518
("se.bsnet.fukt.Mandos", bus,
2566
2520
except dbus.exceptions.NameExistsException as e:
2567
2521
logger.error("Disabling D-Bus:", exc_info=e)
2568
2522
use_dbus = False
2570
2524
tcp_server.use_dbus = False
2572
2526
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2573
service = AvahiServiceToSyslog(
2574
name = server_settings["servicename"],
2575
servicetype = "_mandos._tcp",
2576
protocol = protocol,
2527
service = AvahiServiceToSyslog(name =
2528
server_settings["servicename"],
2529
servicetype = "_mandos._tcp",
2530
protocol = protocol, bus = bus)
2578
2531
if server_settings["interface"]:
2579
service.interface = if_nametoindex(
2580
server_settings["interface"].encode("utf-8"))
2532
service.interface = (if_nametoindex
2533
(server_settings["interface"]
2582
2536
global multiprocessing_manager
2583
2537
multiprocessing_manager = multiprocessing.Manager()
2602
2556
if server_settings["restore"]:
2604
2558
with open(stored_state_path, "rb") as stored_state:
2605
clients_data, old_client_settings = pickle.load(
2559
clients_data, old_client_settings = (pickle.load
2607
2561
os.remove(stored_state_path)
2608
2562
except IOError as e:
2609
2563
if e.errno == errno.ENOENT:
2610
logger.warning("Could not load persistent state:"
2611
" {}".format(os.strerror(e.errno)))
2564
logger.warning("Could not load persistent state: {}"
2565
.format(os.strerror(e.errno)))
2613
2567
logger.critical("Could not load persistent state:",
2616
2570
except EOFError as e:
2617
2571
logger.warning("Could not load persistent state: "
2572
"EOFError:", exc_info=e)
2621
2574
with PGPEngine() as pgp:
2622
2575
for client_name, client in clients_data.items():
2651
2604
if not client["last_checked_ok"]:
2652
2605
logger.warning(
2653
2606
"disabling client {} - Client never "
2654
"performed a successful checker".format(
2607
"performed a successful checker"
2608
.format(client_name))
2656
2609
client["enabled"] = False
2657
2610
elif client["last_checker_status"] != 0:
2658
2611
logger.warning(
2659
2612
"disabling client {} - Client last"
2660
" checker failed with error code"
2663
client["last_checker_status"]))
2613
" checker failed with error code {}"
2614
.format(client_name,
2615
client["last_checker_status"]))
2664
2616
client["enabled"] = False
2666
client["expires"] = (
2667
datetime.datetime.utcnow()
2668
+ client["timeout"])
2618
client["expires"] = (datetime.datetime
2620
+ client["timeout"])
2669
2621
logger.debug("Last checker succeeded,"
2670
" keeping {} enabled".format(
2622
" keeping {} enabled"
2623
.format(client_name))
2673
client["secret"] = pgp.decrypt(
2674
client["encrypted_secret"],
2675
client_settings[client_name]["secret"])
2625
client["secret"] = (
2626
pgp.decrypt(client["encrypted_secret"],
2627
client_settings[client_name]
2676
2629
except PGPError:
2677
2630
# If decryption fails, we use secret from new settings
2678
logger.debug("Failed to decrypt {} old secret".format(
2680
client["secret"] = (client_settings[client_name]
2631
logger.debug("Failed to decrypt {} old secret"
2632
.format(client_name))
2633
client["secret"] = (
2634
client_settings[client_name]["secret"])
2683
2636
# Add/remove clients based on new changes made to config
2684
2637
for client_name in (set(old_client_settings)
2691
2644
# Create all client objects
2692
2645
for client_name, client in clients_data.items():
2693
2646
tcp_server.clients[client_name] = client_class(
2647
name = client_name, settings = client,
2696
2648
server_settings = server_settings)
2698
2650
if not tcp_server.clients:
2714
2666
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2718
@alternate_dbus_interfaces(
2719
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2669
@alternate_dbus_interfaces({"se.recompile.Mandos":
2670
"se.bsnet.fukt.Mandos"})
2720
2671
class MandosDBusService(DBusObjectWithProperties):
2721
2672
"""A D-Bus proxy object"""
2723
2673
def __init__(self):
2724
2674
dbus.service.Object.__init__(self, bus, "/")
2726
2675
_interface = "se.recompile.Mandos"
2728
2677
@dbus_interface_annotations(_interface)
2729
2678
def _foo(self):
2731
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2679
return { "org.freedesktop.DBus.Property"
2680
".EmitsChangedSignal":
2734
2683
@dbus.service.signal(_interface, signature="o")
2735
2684
def ClientAdded(self, objpath):
2757
2707
def GetAllClientsWithProperties(self):
2759
2709
return dbus.Dictionary(
2760
{ c.dbus_object_path: c.GetAll("")
2761
for c in tcp_server.clients.itervalues() },
2710
((c.dbus_object_path, c.GetAll(""))
2711
for c in tcp_server.clients.itervalues()),
2762
2712
signature="oa{sv}")
2764
2714
@dbus.service.method(_interface, in_signature="o")
2805
2755
exclude = { "bus", "changedstate", "secret",
2806
2756
"checker", "server_settings" }
2807
for name, typ in inspect.getmembers(dbus.service
2757
for name, typ in (inspect.getmembers
2758
(dbus.service.Object)):
2809
2759
exclude.add(name)
2811
2761
client_dict["encrypted_secret"] = (client
2818
2768
del client_settings[client.name]["secret"]
2821
with tempfile.NamedTemporaryFile(
2825
dir=os.path.dirname(stored_state_path),
2826
delete=False) as stored_state:
2771
with (tempfile.NamedTemporaryFile
2772
(mode='wb', suffix=".pickle", prefix='clients-',
2773
dir=os.path.dirname(stored_state_path),
2774
delete=False)) as stored_state:
2827
2775
pickle.dump((clients, client_settings), stored_state)
2828
tempname = stored_state.name
2776
tempname=stored_state.name
2829
2777
os.rename(tempname, stored_state_path)
2830
2778
except (IOError, OSError) as e: