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
101
if_nametoindex = ctypes.cdll.LoadLibrary(
102
ctypes.util.find_library("c")).if_nametoindex
101
if_nametoindex = (ctypes.cdll.LoadLibrary
102
(ctypes.util.find_library("c"))
103
104
except (OSError, AttributeError):
105
105
def if_nametoindex(interface):
106
106
"Get an interface index the hard way, i.e. using fcntl()"
107
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
116
116
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler(
120
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
address = "/dev/log"))
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
122
123
syslogger.setFormatter(logging.Formatter
123
124
('Mandos [%(process)d]: %(levelname)s:'
187
187
def encrypt(self, data, password):
188
188
passphrase = self.password_encode(password)
189
with tempfile.NamedTemporaryFile(
190
dir=self.tempdir) as passfile:
189
with tempfile.NamedTemporaryFile(dir=self.tempdir
191
191
passfile.write(passphrase)
193
193
proc = subprocess.Popen(['gpg', '--symmetric',
205
205
def decrypt(self, data, password):
206
206
passphrase = self.password_encode(password)
207
with tempfile.NamedTemporaryFile(
208
dir = self.tempdir) as passfile:
207
with tempfile.NamedTemporaryFile(dir = self.tempdir
209
209
passfile.write(passphrase)
211
211
proc = subprocess.Popen(['gpg', '--decrypt',
257
256
bus: dbus.SystemBus()
261
interface = avahi.IF_UNSPEC,
269
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):
271
263
self.interface = interface
273
265
self.type = servicetype
290
282
" after %i retries, exiting.",
291
283
self.rename_count)
292
284
raise AvahiServiceError("Too many renames")
294
self.server.GetAlternativeServiceName(self.name))
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
295
287
self.rename_count += 1
296
288
logger.info("Changing Zeroconf service name to %r ...",
368
361
def server_state_changed(self, state, error=None):
369
362
"""Derived from the Avahi example code"""
370
363
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",
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" }
377
371
if state in bad_states:
378
372
if bad_states[state] is not None:
379
373
if error is None:
398
392
follow_name_owner_changes=True),
399
393
avahi.DBUS_INTERFACE_SERVER)
400
394
self.server.connect_to_signal("StateChanged",
401
self.server_state_changed)
395
self.server_state_changed)
402
396
self.server_state_changed(self.server.GetState())
406
400
def rename(self, *args, **kwargs):
407
401
"""Add the new name to the syslog messages"""
408
402
ret = AvahiService.rename(self, *args, **kwargs)
409
syslogger.setFormatter(logging.Formatter(
410
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
403
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
405
' %(levelname)s: %(message)s'
461
456
"fingerprint", "host", "interval",
462
457
"last_approval_request", "last_checked_ok",
463
458
"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",
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",
477
471
def config_parser(config):
543
534
self.expires = None
545
536
logger.debug("Creating client %r", self.name)
537
# Uppercase and remove spaces from fingerprint for later
538
# comparison purposes with return value from the fingerprint()
546
540
logger.debug(" Fingerprint: %s", self.fingerprint)
547
541
self.created = settings.get("created",
548
542
datetime.datetime.utcnow())
555
549
self.current_checker_command = None
556
550
self.approved = None
557
551
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()
552
self.changedstate = (multiprocessing_manager
553
.Condition(multiprocessing_manager
555
self.client_structure = [attr for attr in
556
self.__dict__.iterkeys()
562
557
if not attr.startswith("_")]
563
558
self.client_structure.append("client_structure")
565
for name, t in inspect.getmembers(
566
type(self), lambda obj: isinstance(obj, property)):
560
for name, t in inspect.getmembers(type(self),
567
564
if not name.startswith("_"):
568
565
self.client_structure.append(name)
611
608
# and every interval from then on.
612
609
if self.checker_initiator_tag is not None:
613
610
gobject.source_remove(self.checker_initiator_tag)
614
self.checker_initiator_tag = gobject.timeout_add(
615
int(self.interval.total_seconds() * 1000),
611
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
617
615
# Schedule a disable() when 'timeout' has passed
618
616
if self.disable_initiator_tag is not None:
619
617
gobject.source_remove(self.disable_initiator_tag)
620
self.disable_initiator_tag = gobject.timeout_add(
621
int(self.timeout.total_seconds() * 1000), self.disable)
618
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
622
622
# Also start a new checker *right now*.
623
623
self.start_checker()
653
654
gobject.source_remove(self.disable_initiator_tag)
654
655
self.disable_initiator_tag = None
655
656
if getattr(self, "enabled", False):
656
self.disable_initiator_tag = gobject.timeout_add(
657
int(timeout.total_seconds() * 1000), self.disable)
657
self.disable_initiator_tag = (gobject.timeout_add
658
(int(timeout.total_seconds()
659
* 1000), self.disable))
658
660
self.expires = datetime.datetime.utcnow() + timeout
660
662
def need_approval(self):
691
693
# Start a new checker if needed
692
694
if self.checker is None:
693
695
# Escape attributes for the shell
695
attr: re.escape(str(getattr(self, attr)))
696
for attr in self.runtime_expansions }
696
escaped_attrs = { attr:
697
re.escape(str(getattr(self, attr)))
698
for attr in self.runtime_expansions }
698
700
command = self.checker_command % escaped_attrs
699
701
except TypeError as error:
700
702
logger.error('Could not format string "%s"',
701
self.checker_command,
703
return True # Try again later
703
self.checker_command, exc_info=error)
704
return True # Try again later
704
705
self.current_checker_command = command
706
logger.info("Starting checker %r for %s", command,
707
logger.info("Starting checker %r for %s",
708
709
# We don't need to redirect stdout and stderr, since
709
710
# in normal mode, that is already done by daemon(),
710
711
# and in debug mode we don't want to. (Stdin is
719
720
"stderr": wnull })
720
721
self.checker = subprocess.Popen(command,
725
725
except OSError as error:
726
726
logger.error("Failed to start subprocess",
729
self.checker_callback_tag = gobject.child_watch_add(
730
self.checker.pid, self.checker_callback, data=command)
729
self.checker_callback_tag = (gobject.child_watch_add
731
self.checker_callback,
731
733
# The checker may have completed before the gobject
732
734
# watch was added. Check for this.
764
766
self.checker = None
767
def dbus_service_property(dbus_interface,
769
def dbus_service_property(dbus_interface, signature="v",
770
access="readwrite", byte_arrays=False):
771
771
"""Decorators for marking methods of a DBusObjectWithProperties to
772
772
become properties on the D-Bus.
878
871
def _get_all_dbus_things(self, thing):
879
872
"""Returns a generator of (name, attribute) pairs
881
return ((getattr(athing.__get__(self), "_dbus_name", name),
874
return ((getattr(athing.__get__(self), "_dbus_name",
882
876
athing.__get__(self))
883
877
for cls in self.__class__.__mro__
884
878
for name, athing in
885
inspect.getmembers(cls, self._is_dbus_thing(thing)))
879
inspect.getmembers(cls,
880
self._is_dbus_thing(thing)))
887
882
def _get_dbus_property(self, interface_name, property_name):
888
883
"""Returns a bound method if one exists which is a D-Bus
889
884
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")):
886
for cls in self.__class__.__mro__:
887
for name, value in (inspect.getmembers
889
self._is_dbus_thing("property"))):
894
890
if (value._dbus_name == property_name
895
891
and value._dbus_interface == interface_name):
896
892
return value.__get__(self)
898
894
# No such property
899
raise DBusPropertyNotFound("{}:{}.{}".format(
900
self.dbus_object_path, interface_name, property_name))
895
raise DBusPropertyNotFound(self.dbus_object_path + ":"
896
+ interface_name + "."
902
@dbus.service.method(dbus.PROPERTIES_IFACE,
899
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
900
out_signature="v")
905
901
def Get(self, interface_name, property_name):
906
902
"""Standard D-Bus property Get() method, see D-Bus standard.
953
948
if not hasattr(value, "variant_level"):
954
949
properties[name] = value
956
properties[name] = type(value)(
957
value, variant_level = value.variant_level + 1)
951
properties[name] = type(value)(value, variant_level=
952
value.variant_level+1)
958
953
return dbus.Dictionary(properties, signature="sv")
960
955
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
980
975
document = xml.dom.minidom.parseString(xmlstring)
982
976
def make_tag(document, name, prop):
983
977
e = document.createElement("property")
984
978
e.setAttribute("name", name)
985
979
e.setAttribute("type", prop._dbus_signature)
986
980
e.setAttribute("access", prop._dbus_access)
989
982
for if_tag in document.getElementsByTagName("interface"):
990
983
# Add property tags
991
984
for tag in (make_tag(document, name, prop)
1051
1046
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1053
1048
return dbus.String("", variant_level = variant_level)
1054
return dbus.String(dt.isoformat(), variant_level=variant_level)
1049
return dbus.String(dt.isoformat(),
1050
variant_level=variant_level)
1057
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1088
1083
# Ignore non-D-Bus attributes, and D-Bus attributes
1089
1084
# with the wrong interface name
1090
1085
if (not hasattr(attribute, "_dbus_interface")
1091
or not attribute._dbus_interface.startswith(
1092
orig_interface_name)):
1086
or not attribute._dbus_interface
1087
.startswith(orig_interface_name)):
1094
1089
# Create an alternate D-Bus interface name based on
1095
1090
# the current name
1096
alt_interface = attribute._dbus_interface.replace(
1097
orig_interface_name, alt_interface_name)
1091
alt_interface = (attribute._dbus_interface
1092
.replace(orig_interface_name,
1093
alt_interface_name))
1098
1094
interface_names.add(alt_interface)
1099
1095
# Is this a D-Bus signal?
1100
1096
if getattr(attribute, "_dbus_is_signal", False):
1101
1097
# Extract the original non-method undecorated
1102
1098
# function by black magic
1103
1099
nonmethod_func = (dict(
1104
zip(attribute.func_code.co_freevars,
1105
attribute.__closure__))
1106
["func"].cell_contents)
1100
zip(attribute.func_code.co_freevars,
1101
attribute.__closure__))["func"]
1107
1103
# Create a new, but exactly alike, function
1108
1104
# object, and decorate it to be a new D-Bus signal
1109
1105
# with the alternate D-Bus interface name
1110
new_function = (dbus.service.signal(
1111
alt_interface, attribute._dbus_signature)
1106
new_function = (dbus.service.signal
1108
attribute._dbus_signature)
1112
1109
(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)))
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)))
1118
1115
# Copy annotations, if any
1120
new_function._dbus_annotations = dict(
1121
attribute._dbus_annotations)
1117
new_function._dbus_annotations = (
1118
dict(attribute._dbus_annotations))
1122
1119
except AttributeError:
1124
1121
# Define a creator of a function to call both the
1129
1126
"""This function is a scope container to pass
1130
1127
func1 and func2 to the "call_both" function
1131
1128
outside of its arguments"""
1133
1129
def call_both(*args, **kwargs):
1134
1130
"""This function will emit two D-Bus
1135
1131
signals by calling func1 and func2"""
1136
1132
func1(*args, **kwargs)
1137
1133
func2(*args, **kwargs)
1139
1134
return call_both
1140
1135
# Create the "call_both" function and add it to
1146
1141
# object. Decorate it to be a new D-Bus method
1147
1142
# with the alternate D-Bus interface name. Add it
1148
1143
# 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)))
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)))
1159
1154
# Copy annotations, if any
1161
attr[attrname]._dbus_annotations = dict(
1162
attribute._dbus_annotations)
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1163
1158
except AttributeError:
1165
1160
# Is this a D-Bus property?
1168
1163
# object, and decorate it to be a new D-Bus
1169
1164
# property with the alternate D-Bus interface
1170
1165
# 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)))
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)))
1182
1179
# Copy annotations, if any
1184
attr[attrname]._dbus_annotations = dict(
1185
attribute._dbus_annotations)
1181
attr[attrname]._dbus_annotations = (
1182
dict(attribute._dbus_annotations))
1186
1183
except AttributeError:
1188
1185
# Is this a D-Bus interface?
1191
1188
# object. Decorate it to be a new D-Bus interface
1192
1189
# with the alternate D-Bus interface name. Add it
1193
1190
# 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)))
1191
attr[attrname] = (dbus_interface_annotations
1194
(attribute.func_code,
1195
attribute.func_globals,
1196
attribute.func_name,
1197
attribute.func_defaults,
1198
attribute.func_closure)))
1202
1200
# Deprecate all alternate interfaces
1203
1201
iname="_AlternateDBusNames_interface_annotation{}"
1204
1202
for interface_name in interface_names:
1206
1203
@dbus_interface_annotations(interface_name)
1207
1204
def func(self):
1208
1205
return { "org.freedesktop.DBus.Deprecated":
1210
1207
# Find an unused name
1211
1208
for aname in (iname.format(i)
1212
1209
for i in itertools.count()):
1217
1214
# Replace the class with a new subclass of it with
1218
1215
# methods, signals, etc. as created above.
1219
1216
cls = type(b"{}Alternate".format(cls.__name__),
1226
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
"se.bsnet.fukt.Mandos"})
1223
"se.bsnet.fukt.Mandos"})
1228
1224
class ClientDBus(Client, DBusObjectWithProperties):
1229
1225
"""A Client class using D-Bus
1248
1244
client_object_name = str(self.name).translate(
1249
1245
{ord("."): ord("_"),
1250
1246
ord("-"): ord("_")})
1251
self.dbus_object_path = dbus.ObjectPath(
1252
"/clients/" + client_object_name)
1247
self.dbus_object_path = (dbus.ObjectPath
1248
("/clients/" + client_object_name))
1253
1249
DBusObjectWithProperties.__init__(self, self.bus,
1254
1250
self.dbus_object_path)
1256
def notifychangeproperty(transform_func, dbus_name,
1257
type_func=lambda x: x,
1259
invalidate_only=False,
1252
def notifychangeproperty(transform_func,
1253
dbus_name, type_func=lambda x: x,
1254
variant_level=1, invalidate_only=False,
1260
1255
_interface=_interface):
1261
1256
""" Modify a variable so that it's a property which announces
1262
1257
its changes to DBus.
1269
1264
variant_level: D-Bus variant level. Default: 1
1271
1266
attrname = "_{}".format(dbus_name)
1273
1267
def setter(self, value):
1274
1268
if hasattr(self, "dbus_object_path"):
1275
1269
if (not hasattr(self, attrname) or
1276
1270
type_func(getattr(self, attrname, None))
1277
1271
!= type_func(value)):
1278
1272
if invalidate_only:
1279
self.PropertiesChanged(
1280
_interface, dbus.Dictionary(),
1281
dbus.Array((dbus_name, )))
1273
self.PropertiesChanged(_interface,
1283
dbus_value = transform_func(
1285
variant_level = variant_level)
1278
dbus_value = transform_func(type_func(value),
1286
1281
self.PropertyChanged(dbus.String(dbus_name),
1288
self.PropertiesChanged(
1290
dbus.Dictionary({ dbus.String(dbus_name):
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1293
1287
setattr(self, attrname, value)
1295
1289
return property(lambda self: getattr(self, attrname), setter)
1301
1295
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1296
last_enabled = notifychangeproperty(datetime_to_dbus,
1304
checker = notifychangeproperty(
1305
dbus.Boolean, "CheckerRunning",
1306
type_func = lambda checker: checker is not None)
1298
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1299
type_func = lambda checker:
1300
checker is not None)
1307
1301
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1302
"LastCheckedOK")
1309
1303
last_checker_status = notifychangeproperty(dbus.Int16,
1312
1306
datetime_to_dbus, "LastApprovalRequest")
1313
1307
approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1308
"ApprovedByDefault")
1315
approval_delay = notifychangeproperty(
1316
dbus.UInt64, "ApprovalDelay",
1317
type_func = lambda td: td.total_seconds() * 1000)
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1312
lambda td: td.total_seconds()
1318
1314
approval_duration = notifychangeproperty(
1319
1315
dbus.UInt64, "ApprovalDuration",
1320
1316
type_func = lambda td: td.total_seconds() * 1000)
1321
1317
host = notifychangeproperty(dbus.String, "Host")
1322
timeout = notifychangeproperty(
1323
dbus.UInt64, "Timeout",
1324
type_func = lambda td: td.total_seconds() * 1000)
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1325
1321
extended_timeout = notifychangeproperty(
1326
1322
dbus.UInt64, "ExtendedTimeout",
1327
1323
type_func = lambda td: td.total_seconds() * 1000)
1328
interval = notifychangeproperty(
1329
dbus.UInt64, "Interval",
1330
type_func = lambda td: td.total_seconds() * 1000)
1324
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1331
1329
checker_command = notifychangeproperty(dbus.String, "Checker")
1332
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
1331
invalidate_only=True)
1471
1469
return dbus.Boolean(bool(self.approvals_pending))
1473
1471
# ApprovedByDefault - property
1474
@dbus_service_property(_interface,
1472
@dbus_service_property(_interface, signature="b",
1476
1473
access="readwrite")
1477
1474
def ApprovedByDefault_dbus_property(self, value=None):
1478
1475
if value is None: # get
1480
1477
self.approved_by_default = bool(value)
1482
1479
# ApprovalDelay - property
1483
@dbus_service_property(_interface,
1480
@dbus_service_property(_interface, signature="t",
1485
1481
access="readwrite")
1486
1482
def ApprovalDelay_dbus_property(self, value=None):
1487
1483
if value is None: # get
1490
1486
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1492
1488
# ApprovalDuration - property
1493
@dbus_service_property(_interface,
1489
@dbus_service_property(_interface, signature="t",
1495
1490
access="readwrite")
1496
1491
def ApprovalDuration_dbus_property(self, value=None):
1497
1492
if value is None: # get
1551
1543
return datetime_to_dbus(self.last_checked_ok)
1553
1545
# LastCheckerStatus - property
1554
@dbus_service_property(_interface, signature="n", access="read")
1546
@dbus_service_property(_interface, signature="n",
1555
1548
def LastCheckerStatus_dbus_property(self):
1556
1549
return dbus.Int16(self.last_checker_status)
1588
1580
gobject.source_remove(self.disable_initiator_tag)
1589
self.disable_initiator_tag = gobject.timeout_add(
1590
int((self.expires - now).total_seconds() * 1000),
1581
self.disable_initiator_tag = (
1582
gobject.timeout_add(
1583
int((self.expires - now).total_seconds()
1584
* 1000), self.disable))
1593
1586
# ExtendedTimeout - property
1594
@dbus_service_property(_interface,
1587
@dbus_service_property(_interface, signature="t",
1596
1588
access="readwrite")
1597
1589
def ExtendedTimeout_dbus_property(self, value=None):
1598
1590
if value is None: # get
1601
1593
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1603
1595
# Interval - property
1604
@dbus_service_property(_interface,
1596
@dbus_service_property(_interface, signature="t",
1606
1597
access="readwrite")
1607
1598
def Interval_dbus_property(self, value=None):
1608
1599
if value is None: # get
1613
1604
if self.enabled:
1614
1605
# Reschedule checker run
1615
1606
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
1607
self.checker_initiator_tag = (gobject.timeout_add
1608
(value, self.start_checker))
1609
self.start_checker() # Start one now, too
1620
1611
# Checker - property
1621
@dbus_service_property(_interface,
1612
@dbus_service_property(_interface, signature="s",
1623
1613
access="readwrite")
1624
1614
def Checker_dbus_property(self, value=None):
1625
1615
if value is None: # get
1644
1633
return self.dbus_object_path # is already a dbus.ObjectPath
1646
1635
# Secret = property
1647
@dbus_service_property(_interface,
1636
@dbus_service_property(_interface, signature="ay",
1637
access="write", byte_arrays=True)
1651
1638
def Secret_dbus_property(self, value):
1652
1639
self.secret = bytes(value)
1669
1656
if data[0] == 'data':
1671
1658
if data[0] == 'function':
1673
1659
def func(*args, **kwargs):
1674
1660
self._pipe.send(('funcall', name, args, kwargs))
1675
1661
return self._pipe.recv()[1]
1679
1664
def __setattr__(self, name, value):
1695
1680
logger.debug("Pipe FD: %d",
1696
1681
self.server.child_pipe.fileno())
1698
session = gnutls.connection.ClientSession(
1699
self.request, gnutls.connection .X509Credentials())
1683
session = (gnutls.connection
1684
.ClientSession(self.request,
1686
.X509Credentials()))
1701
1688
# Note: gnutls.connection.X509Credentials is really a
1702
1689
# generic GnuTLS certificate credentials object so long as
1711
1698
priority = self.server.gnutls_priority
1712
1699
if priority is None:
1713
1700
priority = "NORMAL"
1714
gnutls.library.functions.gnutls_priority_set_direct(
1715
session._c_object, priority, None)
1701
(gnutls.library.functions
1702
.gnutls_priority_set_direct(session._c_object,
1717
1705
# Start communication using the Mandos protocol
1718
1706
# Get protocol number
1813
1801
logger.warning("gnutls send failed",
1814
1802
exc_info=error)
1816
logger.debug("Sent: %d, remaining: %d", sent,
1817
len(client.secret) - (sent_size
1804
logger.debug("Sent: %d, remaining: %d",
1805
sent, len(client.secret)
1806
- (sent_size + sent))
1819
1807
sent_size += sent
1821
1809
logger.info("Sending secret to %s", client.name)
1838
1826
def peer_certificate(session):
1839
1827
"Return the peer's OpenPGP certificate as a bytestring"
1840
1828
# If not an OpenPGP certificate...
1841
if (gnutls.library.functions.gnutls_certificate_type_get(
1829
if (gnutls.library.functions
1830
.gnutls_certificate_type_get(session._c_object)
1843
1831
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1832
# ...do the normal thing
1845
1833
return session.peer_certificate
1859
1847
def fingerprint(openpgp):
1860
1848
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1849
# 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)))
1850
datum = (gnutls.library.types
1851
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1854
ctypes.c_uint(len(openpgp))))
1866
1855
# New empty GnuTLS certificate
1867
1856
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
gnutls.library.functions.gnutls_openpgp_crt_init(
1857
(gnutls.library.functions
1858
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1859
# 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)
1860
(gnutls.library.functions
1861
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1862
gnutls.library.constants
1863
.GNUTLS_OPENPGP_FMT_RAW))
1874
1864
# Verify the self signature in the key
1875
1865
crtverify = ctypes.c_uint()
1876
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
crt, 0, ctypes.byref(crtverify))
1866
(gnutls.library.functions
1867
.gnutls_openpgp_crt_verify_self(crt, 0,
1868
ctypes.byref(crtverify)))
1878
1869
if crtverify.value != 0:
1879
1870
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
raise gnutls.errors.CertificateSecurityError(
1871
raise (gnutls.errors.CertificateSecurityError
1882
1873
# New buffer for the fingerprint
1883
1874
buf = ctypes.create_string_buffer(20)
1884
1875
buf_len = ctypes.c_size_t()
1885
1876
# 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))
1877
(gnutls.library.functions
1878
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1879
ctypes.byref(buf_len)))
1888
1880
# Deinit the certificate
1889
1881
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1882
# Convert the buffer to a Python bytestring
1941
1931
interface: None or a network interface name (string)
1942
1932
use_ipv6: Boolean; to use IPv6 or not
1945
1934
def __init__(self, server_address, RequestHandlerClass,
1935
interface=None, use_ipv6=True, socketfd=None):
1949
1936
"""If socketfd is set, use that file descriptor instead of
1950
1937
creating a new one with socket.socket().
1992
1979
self.interface)
1995
self.socket.setsockopt(
1996
socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
(self.interface + "\0").encode("utf-8"))
1982
self.socket.setsockopt(socket.SOL_SOCKET,
1984
(self.interface + "\0")
1998
1986
except socket.error as error:
1999
1987
if error.errno == errno.EPERM:
2000
1988
logger.error("No permission to bind to"
2018
2006
self.server_address = (any_address,
2019
2007
self.server_address[1])
2020
2008
elif not self.server_address[1]:
2021
self.server_address = (self.server_address[0], 0)
2009
self.server_address = (self.server_address[0],
2022
2011
# if self.interface:
2023
2012
# self.server_address = (self.server_address[0],
2039
2028
Assumes a gobject.MainLoop event loop.
2042
2030
def __init__(self, server_address, RequestHandlerClass,
2046
gnutls_priority=None,
2031
interface=None, use_ipv6=True, clients=None,
2032
gnutls_priority=None, use_dbus=True, socketfd=None):
2049
2033
self.enabled = False
2050
2034
self.clients = clients
2051
2035
if self.clients is None:
2068
2051
def add_pipe(self, parent_pipe, proc):
2069
2052
# 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,
2053
gobject.io_add_watch(parent_pipe.fileno(),
2054
gobject.IO_IN | gobject.IO_HUP,
2055
functools.partial(self.handle_ipc,
2077
def handle_ipc(self, source, condition,
2080
client_object=None):
2060
def handle_ipc(self, source, condition, parent_pipe=None,
2061
proc = None, client_object=None):
2081
2062
# error, or the other end of multiprocessing.Pipe has closed
2082
2063
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2064
# Wait for other process to exit
2106
2087
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))
2090
gobject.io_add_watch(parent_pipe.fileno(),
2091
gobject.IO_IN | gobject.IO_HUP,
2092
functools.partial(self.handle_ipc,
2116
2098
parent_pipe.send(True)
2117
2099
# remove the old hook in favor of the new above hook on
2125
2107
parent_pipe.send(('data', getattr(client_object,
2126
2108
funcname)(*args,
2129
2111
if command == 'getattr':
2130
2112
attrname = request[1]
2131
2113
if callable(client_object.__getattribute__(attrname)):
2132
parent_pipe.send(('function', ))
2114
parent_pipe.send(('function',))
2135
'data', client_object.__getattribute__(attrname)))
2116
parent_pipe.send(('data', client_object
2117
.__getattribute__(attrname)))
2137
2119
if command == 'setattr':
2138
2120
attrname = request[1]
2179
2161
"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
2163
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
2164
# the "duration" ABNF definition in RFC 3339, Appendix A.
2188
2165
token_end = Token(re.compile(r"$"), None, frozenset())
2189
2166
token_second = Token(re.compile(r"(\d+)S"),
2190
2167
datetime.timedelta(seconds=1),
2191
frozenset((token_end, )))
2168
frozenset((token_end,)))
2192
2169
token_minute = Token(re.compile(r"(\d+)M"),
2193
2170
datetime.timedelta(minutes=1),
2194
2171
frozenset((token_second, token_end)))
2210
2187
frozenset((token_month, token_end)))
2211
2188
token_week = Token(re.compile(r"(\d+)W"),
2212
2189
datetime.timedelta(weeks=1),
2213
frozenset((token_end, )))
2190
frozenset((token_end,)))
2214
2191
token_duration = Token(re.compile(r"P"), None,
2215
2192
frozenset((token_year, token_month,
2216
2193
token_day, token_time,
2306
2284
# Close all standard open file descriptors
2307
2285
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2286
if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
raise OSError(errno.ENODEV,
2310
"{} not a character device"
2287
raise OSError(errno.ENODEV, "{} not a character device"
2311
2288
.format(os.devnull))
2312
2289
os.dup2(null, sys.stdin.fileno())
2313
2290
os.dup2(null, sys.stdout.fileno())
2390
2366
"statedir": "/var/lib/mandos",
2391
2367
"foreground": "False",
2392
2368
"zeroconf": "True",
2395
2371
# Parse config file for server-global settings
2396
2372
server_config = configparser.SafeConfigParser(server_defaults)
2397
2373
del server_defaults
2398
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2374
server_config.read(os.path.join(options.configdir,
2399
2376
# Convert the SafeConfigParser object to a dict
2400
2377
server_settings = server_config.defaults()
2401
2378
# Use the appropriate methods on the non-string config options
2419
2396
# Override the settings from the config file with command line
2420
2397
# options, if set.
2421
2398
for option in ("interface", "address", "port", "debug",
2422
"priority", "servicename", "configdir", "use_dbus",
2423
"use_ipv6", "debuglevel", "restore", "statedir",
2424
"socket", "foreground", "zeroconf"):
2399
"priority", "servicename", "configdir",
2400
"use_dbus", "use_ipv6", "debuglevel", "restore",
2401
"statedir", "socket", "foreground", "zeroconf"):
2425
2402
value = getattr(options, option)
2426
2403
if value is not None:
2427
2404
server_settings[option] = value
2443
2420
##################################################################
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")
2422
if (not server_settings["zeroconf"] and
2423
not (server_settings["port"]
2424
or server_settings["socket"] != "")):
2425
parser.error("Needs port or socket to work without"
2450
2428
# For convenience
2451
2429
debug = server_settings["debug"]
2467
2445
initlogger(debug, level)
2469
2447
if server_settings["servicename"] != "Mandos":
2470
syslogger.setFormatter(
2471
logging.Formatter('Mandos ({}) [%(process)d]:'
2472
' %(levelname)s: %(message)s'.format(
2473
server_settings["servicename"])))
2448
syslogger.setFormatter(logging.Formatter
2449
('Mandos ({}) [%(process)d]:'
2450
' %(levelname)s: %(message)s'
2451
.format(server_settings
2475
2454
# Parse config file with clients
2476
2455
client_config = configparser.SafeConfigParser(Client
2484
2463
socketfd = None
2485
2464
if server_settings["socket"] != "":
2486
2465
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"],
2466
tcp_server = MandosServer((server_settings["address"],
2467
server_settings["port"]),
2469
interface=(server_settings["interface"]
2473
server_settings["priority"],
2495
2476
if not foreground:
2496
2477
pidfilename = "/run/mandos.pid"
2497
2478
if not os.path.isdir("/run/."):
2531
2512
def debug_gnutls(level, string):
2532
2513
logger.debug("GnuTLS: %s", string[:-1])
2534
gnutls.library.functions.gnutls_global_set_log_function(
2515
(gnutls.library.functions
2516
.gnutls_global_set_log_function(debug_gnutls))
2537
2518
# Redirect stdin so all checkers get /dev/null
2538
2519
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2560
2541
bus_name = dbus.service.BusName("se.recompile.Mandos",
2563
old_bus_name = dbus.service.BusName(
2564
"se.bsnet.fukt.Mandos", bus,
2542
bus, do_not_queue=True)
2543
old_bus_name = (dbus.service.BusName
2544
("se.bsnet.fukt.Mandos", bus,
2566
2546
except dbus.exceptions.NameExistsException as e:
2567
2547
logger.error("Disabling D-Bus:", exc_info=e)
2568
2548
use_dbus = False
2570
2550
tcp_server.use_dbus = False
2572
2552
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,
2553
service = AvahiServiceToSyslog(name =
2554
server_settings["servicename"],
2555
servicetype = "_mandos._tcp",
2556
protocol = protocol, bus = bus)
2578
2557
if server_settings["interface"]:
2579
service.interface = if_nametoindex(
2580
server_settings["interface"].encode("utf-8"))
2558
service.interface = (if_nametoindex
2559
(server_settings["interface"]
2582
2562
global multiprocessing_manager
2583
2563
multiprocessing_manager = multiprocessing.Manager()
2602
2582
if server_settings["restore"]:
2604
2584
with open(stored_state_path, "rb") as stored_state:
2605
clients_data, old_client_settings = pickle.load(
2585
clients_data, old_client_settings = (pickle.load
2607
2587
os.remove(stored_state_path)
2608
2588
except IOError as e:
2609
2589
if e.errno == errno.ENOENT:
2610
logger.warning("Could not load persistent state:"
2611
" {}".format(os.strerror(e.errno)))
2590
logger.warning("Could not load persistent state: {}"
2591
.format(os.strerror(e.errno)))
2613
2593
logger.critical("Could not load persistent state:",
2616
2596
except EOFError as e:
2617
2597
logger.warning("Could not load persistent state: "
2598
"EOFError:", exc_info=e)
2621
2600
with PGPEngine() as pgp:
2622
2601
for client_name, client in clients_data.items():
2651
2630
if not client["last_checked_ok"]:
2652
2631
logger.warning(
2653
2632
"disabling client {} - Client never "
2654
"performed a successful checker".format(
2633
"performed a successful checker"
2634
.format(client_name))
2656
2635
client["enabled"] = False
2657
2636
elif client["last_checker_status"] != 0:
2658
2637
logger.warning(
2659
2638
"disabling client {} - Client last"
2660
" checker failed with error code"
2663
client["last_checker_status"]))
2639
" checker failed with error code {}"
2640
.format(client_name,
2641
client["last_checker_status"]))
2664
2642
client["enabled"] = False
2666
client["expires"] = (
2667
datetime.datetime.utcnow()
2668
+ client["timeout"])
2644
client["expires"] = (datetime.datetime
2646
+ client["timeout"])
2669
2647
logger.debug("Last checker succeeded,"
2670
" keeping {} enabled".format(
2648
" keeping {} enabled"
2649
.format(client_name))
2673
client["secret"] = pgp.decrypt(
2674
client["encrypted_secret"],
2675
client_settings[client_name]["secret"])
2651
client["secret"] = (
2652
pgp.decrypt(client["encrypted_secret"],
2653
client_settings[client_name]
2676
2655
except PGPError:
2677
2656
# 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]
2657
logger.debug("Failed to decrypt {} old secret"
2658
.format(client_name))
2659
client["secret"] = (
2660
client_settings[client_name]["secret"])
2683
2662
# Add/remove clients based on new changes made to config
2684
2663
for client_name in (set(old_client_settings)
2691
2670
# Create all client objects
2692
2671
for client_name, client in clients_data.items():
2693
2672
tcp_server.clients[client_name] = client_class(
2673
name = client_name, settings = client,
2696
2674
server_settings = server_settings)
2698
2676
if not tcp_server.clients:
2714
2692
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2718
@alternate_dbus_interfaces(
2719
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2695
@alternate_dbus_interfaces({"se.recompile.Mandos":
2696
"se.bsnet.fukt.Mandos"})
2720
2697
class MandosDBusService(DBusObjectWithProperties):
2721
2698
"""A D-Bus proxy object"""
2723
2699
def __init__(self):
2724
2700
dbus.service.Object.__init__(self, bus, "/")
2726
2701
_interface = "se.recompile.Mandos"
2728
2703
@dbus_interface_annotations(_interface)
2729
2704
def _foo(self):
2731
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2705
return { "org.freedesktop.DBus.Property"
2706
".EmitsChangedSignal":
2734
2709
@dbus.service.signal(_interface, signature="o")
2735
2710
def ClientAdded(self, objpath):
2805
2781
exclude = { "bus", "changedstate", "secret",
2806
2782
"checker", "server_settings" }
2807
for name, typ in inspect.getmembers(dbus.service
2783
for name, typ in (inspect.getmembers
2784
(dbus.service.Object)):
2809
2785
exclude.add(name)
2811
2787
client_dict["encrypted_secret"] = (client
2818
2794
del client_settings[client.name]["secret"]
2821
with tempfile.NamedTemporaryFile(
2825
dir=os.path.dirname(stored_state_path),
2826
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:
2827
2801
pickle.dump((clients, client_settings), stored_state)
2828
tempname = stored_state.name
2802
tempname=stored_state.name
2829
2803
os.rename(tempname, stored_state_path)
2830
2804
except (IOError, OSError) as e: