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
114
if_nametoindex = ctypes.cdll.LoadLibrary(
115
ctypes.util.find_library("c")).if_nametoindex
101
if_nametoindex = (ctypes.cdll.LoadLibrary
102
(ctypes.util.find_library("c"))
116
104
except (OSError, AttributeError):
118
105
def if_nametoindex(interface):
119
106
"Get an interface index the hard way, i.e. using fcntl()"
120
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
129
116
"""init logger and add loglevel"""
132
syslogger = (logging.handlers.SysLogHandler(
133
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
134
address = "/dev/log"))
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
135
123
syslogger.setFormatter(logging.Formatter
136
124
('Mandos [%(process)d]: %(levelname)s:'
200
187
def encrypt(self, data, password):
201
188
passphrase = self.password_encode(password)
202
with tempfile.NamedTemporaryFile(
203
dir=self.tempdir) as passfile:
189
with tempfile.NamedTemporaryFile(dir=self.tempdir
204
191
passfile.write(passphrase)
206
193
proc = subprocess.Popen(['gpg', '--symmetric',
218
205
def decrypt(self, data, password):
219
206
passphrase = self.password_encode(password)
220
with tempfile.NamedTemporaryFile(
221
dir = self.tempdir) as passfile:
207
with tempfile.NamedTemporaryFile(dir = self.tempdir
222
209
passfile.write(passphrase)
224
211
proc = subprocess.Popen(['gpg', '--decrypt',
270
256
bus: dbus.SystemBus()
274
interface = avahi.IF_UNSPEC,
282
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):
284
263
self.interface = interface
286
265
self.type = servicetype
303
282
" after %i retries, exiting.",
304
283
self.rename_count)
305
284
raise AvahiServiceError("Too many renames")
307
self.server.GetAlternativeServiceName(self.name))
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
308
287
self.rename_count += 1
309
288
logger.info("Changing Zeroconf service name to %r ...",
381
361
def server_state_changed(self, state, error=None):
382
362
"""Derived from the Avahi example code"""
383
363
logger.debug("Avahi server state change: %i", state)
385
avahi.SERVER_INVALID: "Zeroconf server invalid",
386
avahi.SERVER_REGISTERING: None,
387
avahi.SERVER_COLLISION: "Zeroconf server name collision",
388
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" }
390
371
if state in bad_states:
391
372
if bad_states[state] is not None:
392
373
if error is None:
411
392
follow_name_owner_changes=True),
412
393
avahi.DBUS_INTERFACE_SERVER)
413
394
self.server.connect_to_signal("StateChanged",
414
self.server_state_changed)
395
self.server_state_changed)
415
396
self.server_state_changed(self.server.GetState())
419
400
def rename(self, *args, **kwargs):
420
401
"""Add the new name to the syslog messages"""
421
402
ret = AvahiService.rename(self, *args, **kwargs)
422
syslogger.setFormatter(logging.Formatter(
423
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
403
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
405
' %(levelname)s: %(message)s'
474
456
"fingerprint", "host", "interval",
475
457
"last_approval_request", "last_checked_ok",
476
458
"last_enabled", "name", "timeout")
479
"extended_timeout": "PT15M",
481
"checker": "fping -q -- %%(host)s",
483
"approval_delay": "PT0S",
484
"approval_duration": "PT1S",
485
"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",
490
471
def config_parser(config):
568
549
self.current_checker_command = None
569
550
self.approved = None
570
551
self.approvals_pending = 0
571
self.changedstate = multiprocessing_manager.Condition(
572
multiprocessing_manager.Lock())
573
self.client_structure = [attr
574
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()
575
557
if not attr.startswith("_")]
576
558
self.client_structure.append("client_structure")
578
for name, t in inspect.getmembers(
579
type(self), lambda obj: isinstance(obj, property)):
560
for name, t in inspect.getmembers(type(self),
580
564
if not name.startswith("_"):
581
565
self.client_structure.append(name)
624
608
# and every interval from then on.
625
609
if self.checker_initiator_tag is not None:
626
610
gobject.source_remove(self.checker_initiator_tag)
627
self.checker_initiator_tag = gobject.timeout_add(
628
int(self.interval.total_seconds() * 1000),
611
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
630
615
# Schedule a disable() when 'timeout' has passed
631
616
if self.disable_initiator_tag is not None:
632
617
gobject.source_remove(self.disable_initiator_tag)
633
self.disable_initiator_tag = gobject.timeout_add(
634
int(self.timeout.total_seconds() * 1000), self.disable)
618
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
635
622
# Also start a new checker *right now*.
636
623
self.start_checker()
666
654
gobject.source_remove(self.disable_initiator_tag)
667
655
self.disable_initiator_tag = None
668
656
if getattr(self, "enabled", False):
669
self.disable_initiator_tag = gobject.timeout_add(
670
int(timeout.total_seconds() * 1000), self.disable)
657
self.disable_initiator_tag = (gobject.timeout_add
658
(int(timeout.total_seconds()
659
* 1000), self.disable))
671
660
self.expires = datetime.datetime.utcnow() + timeout
673
662
def need_approval(self):
704
693
# Start a new checker if needed
705
694
if self.checker is None:
706
695
# Escape attributes for the shell
708
attr: re.escape(str(getattr(self, attr)))
709
for attr in self.runtime_expansions }
696
escaped_attrs = { attr:
697
re.escape(str(getattr(self, attr)))
698
for attr in self.runtime_expansions }
711
700
command = self.checker_command % escaped_attrs
712
701
except TypeError as error:
713
702
logger.error('Could not format string "%s"',
714
self.checker_command,
716
return True # Try again later
703
self.checker_command, exc_info=error)
704
return True # Try again later
717
705
self.current_checker_command = command
719
logger.info("Starting checker %r for %s", command,
707
logger.info("Starting checker %r for %s",
721
709
# We don't need to redirect stdout and stderr, since
722
710
# in normal mode, that is already done by daemon(),
723
711
# and in debug mode we don't want to. (Stdin is
732
720
"stderr": wnull })
733
721
self.checker = subprocess.Popen(command,
738
725
except OSError as error:
739
726
logger.error("Failed to start subprocess",
742
self.checker_callback_tag = gobject.child_watch_add(
743
self.checker.pid, self.checker_callback, data=command)
729
self.checker_callback_tag = (gobject.child_watch_add
731
self.checker_callback,
744
733
# The checker may have completed before the gobject
745
734
# watch was added. Check for this.
777
766
self.checker = None
780
def dbus_service_property(dbus_interface,
769
def dbus_service_property(dbus_interface, signature="v",
770
access="readwrite", byte_arrays=False):
784
771
"""Decorators for marking methods of a DBusObjectWithProperties to
785
772
become properties on the D-Bus.
891
871
def _get_all_dbus_things(self, thing):
892
872
"""Returns a generator of (name, attribute) pairs
894
return ((getattr(athing.__get__(self), "_dbus_name", name),
874
return ((getattr(athing.__get__(self), "_dbus_name",
895
876
athing.__get__(self))
896
877
for cls in self.__class__.__mro__
897
878
for name, athing in
898
inspect.getmembers(cls, self._is_dbus_thing(thing)))
879
inspect.getmembers(cls,
880
self._is_dbus_thing(thing)))
900
882
def _get_dbus_property(self, interface_name, property_name):
901
883
"""Returns a bound method if one exists which is a D-Bus
902
884
property with the specified name and interface.
904
for cls in self.__class__.__mro__:
905
for name, value in inspect.getmembers(
906
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"))):
907
890
if (value._dbus_name == property_name
908
891
and value._dbus_interface == interface_name):
909
892
return value.__get__(self)
911
894
# No such property
912
raise DBusPropertyNotFound("{}:{}.{}".format(
913
self.dbus_object_path, interface_name, property_name))
895
raise DBusPropertyNotFound(self.dbus_object_path + ":"
896
+ interface_name + "."
915
@dbus.service.method(dbus.PROPERTIES_IFACE,
899
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
917
900
out_signature="v")
918
901
def Get(self, interface_name, property_name):
919
902
"""Standard D-Bus property Get() method, see D-Bus standard.
966
948
if not hasattr(value, "variant_level"):
967
949
properties[name] = value
969
properties[name] = type(value)(
970
value, variant_level = value.variant_level + 1)
951
properties[name] = type(value)(value, variant_level=
952
value.variant_level+1)
971
953
return dbus.Dictionary(properties, signature="sv")
973
955
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
993
975
document = xml.dom.minidom.parseString(xmlstring)
995
976
def make_tag(document, name, prop):
996
977
e = document.createElement("property")
997
978
e.setAttribute("name", name)
998
979
e.setAttribute("type", prop._dbus_signature)
999
980
e.setAttribute("access", prop._dbus_access)
1002
982
for if_tag in document.getElementsByTagName("interface"):
1003
983
# Add property tags
1004
984
for tag in (make_tag(document, name, prop)
1064
1046
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1066
1048
return dbus.String("", variant_level = variant_level)
1067
return dbus.String(dt.isoformat(), variant_level=variant_level)
1049
return dbus.String(dt.isoformat(),
1050
variant_level=variant_level)
1070
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1101
1083
# Ignore non-D-Bus attributes, and D-Bus attributes
1102
1084
# with the wrong interface name
1103
1085
if (not hasattr(attribute, "_dbus_interface")
1104
or not attribute._dbus_interface.startswith(
1105
orig_interface_name)):
1086
or not attribute._dbus_interface
1087
.startswith(orig_interface_name)):
1107
1089
# Create an alternate D-Bus interface name based on
1108
1090
# the current name
1109
alt_interface = attribute._dbus_interface.replace(
1110
orig_interface_name, alt_interface_name)
1091
alt_interface = (attribute._dbus_interface
1092
.replace(orig_interface_name,
1093
alt_interface_name))
1111
1094
interface_names.add(alt_interface)
1112
1095
# Is this a D-Bus signal?
1113
1096
if getattr(attribute, "_dbus_is_signal", False):
1114
1097
# Extract the original non-method undecorated
1115
1098
# function by black magic
1116
1099
nonmethod_func = (dict(
1117
zip(attribute.func_code.co_freevars,
1118
attribute.__closure__))
1119
["func"].cell_contents)
1100
zip(attribute.func_code.co_freevars,
1101
attribute.__closure__))["func"]
1120
1103
# Create a new, but exactly alike, function
1121
1104
# object, and decorate it to be a new D-Bus signal
1122
1105
# with the alternate D-Bus interface name
1123
new_function = (dbus.service.signal(
1124
alt_interface, attribute._dbus_signature)
1106
new_function = (dbus.service.signal
1108
attribute._dbus_signature)
1125
1109
(types.FunctionType(
1126
nonmethod_func.func_code,
1127
nonmethod_func.func_globals,
1128
nonmethod_func.func_name,
1129
nonmethod_func.func_defaults,
1130
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)))
1131
1115
# Copy annotations, if any
1133
new_function._dbus_annotations = dict(
1134
attribute._dbus_annotations)
1117
new_function._dbus_annotations = (
1118
dict(attribute._dbus_annotations))
1135
1119
except AttributeError:
1137
1121
# Define a creator of a function to call both the
1142
1126
"""This function is a scope container to pass
1143
1127
func1 and func2 to the "call_both" function
1144
1128
outside of its arguments"""
1146
1129
def call_both(*args, **kwargs):
1147
1130
"""This function will emit two D-Bus
1148
1131
signals by calling func1 and func2"""
1149
1132
func1(*args, **kwargs)
1150
1133
func2(*args, **kwargs)
1152
1134
return call_both
1153
1135
# Create the "call_both" function and add it to
1159
1141
# object. Decorate it to be a new D-Bus method
1160
1142
# with the alternate D-Bus interface name. Add it
1161
1143
# to the class.
1163
dbus.service.method(
1165
attribute._dbus_in_signature,
1166
attribute._dbus_out_signature)
1167
(types.FunctionType(attribute.func_code,
1168
attribute.func_globals,
1169
attribute.func_name,
1170
attribute.func_defaults,
1171
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)))
1172
1154
# Copy annotations, if any
1174
attr[attrname]._dbus_annotations = dict(
1175
attribute._dbus_annotations)
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1176
1158
except AttributeError:
1178
1160
# Is this a D-Bus property?
1181
1163
# object, and decorate it to be a new D-Bus
1182
1164
# property with the alternate D-Bus interface
1183
1165
# name. Add it to the class.
1184
attr[attrname] = (dbus_service_property(
1185
alt_interface, attribute._dbus_signature,
1186
attribute._dbus_access,
1187
attribute._dbus_get_args_options
1189
(types.FunctionType(
1190
attribute.func_code,
1191
attribute.func_globals,
1192
attribute.func_name,
1193
attribute.func_defaults,
1194
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)))
1195
1179
# Copy annotations, if any
1197
attr[attrname]._dbus_annotations = dict(
1198
attribute._dbus_annotations)
1181
attr[attrname]._dbus_annotations = (
1182
dict(attribute._dbus_annotations))
1199
1183
except AttributeError:
1201
1185
# Is this a D-Bus interface?
1204
1188
# object. Decorate it to be a new D-Bus interface
1205
1189
# with the alternate D-Bus interface name. Add it
1206
1190
# to the class.
1208
dbus_interface_annotations(alt_interface)
1209
(types.FunctionType(attribute.func_code,
1210
attribute.func_globals,
1211
attribute.func_name,
1212
attribute.func_defaults,
1213
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)))
1215
1200
# Deprecate all alternate interfaces
1216
1201
iname="_AlternateDBusNames_interface_annotation{}"
1217
1202
for interface_name in interface_names:
1219
1203
@dbus_interface_annotations(interface_name)
1220
1204
def func(self):
1221
1205
return { "org.freedesktop.DBus.Deprecated":
1223
1207
# Find an unused name
1224
1208
for aname in (iname.format(i)
1225
1209
for i in itertools.count()):
1230
1214
# Replace the class with a new subclass of it with
1231
1215
# methods, signals, etc. as created above.
1232
1216
cls = type(b"{}Alternate".format(cls.__name__),
1239
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1240
"se.bsnet.fukt.Mandos"})
1223
"se.bsnet.fukt.Mandos"})
1241
1224
class ClientDBus(Client, DBusObjectWithProperties):
1242
1225
"""A Client class using D-Bus
1261
1244
client_object_name = str(self.name).translate(
1262
1245
{ord("."): ord("_"),
1263
1246
ord("-"): ord("_")})
1264
self.dbus_object_path = dbus.ObjectPath(
1265
"/clients/" + client_object_name)
1247
self.dbus_object_path = (dbus.ObjectPath
1248
("/clients/" + client_object_name))
1266
1249
DBusObjectWithProperties.__init__(self, self.bus,
1267
1250
self.dbus_object_path)
1269
def notifychangeproperty(transform_func, dbus_name,
1270
type_func=lambda x: x,
1272
invalidate_only=False,
1252
def notifychangeproperty(transform_func,
1253
dbus_name, type_func=lambda x: x,
1254
variant_level=1, invalidate_only=False,
1273
1255
_interface=_interface):
1274
1256
""" Modify a variable so that it's a property which announces
1275
1257
its changes to DBus.
1282
1264
variant_level: D-Bus variant level. Default: 1
1284
1266
attrname = "_{}".format(dbus_name)
1286
1267
def setter(self, value):
1287
1268
if hasattr(self, "dbus_object_path"):
1288
1269
if (not hasattr(self, attrname) or
1289
1270
type_func(getattr(self, attrname, None))
1290
1271
!= type_func(value)):
1291
1272
if invalidate_only:
1292
self.PropertiesChanged(
1293
_interface, dbus.Dictionary(),
1294
dbus.Array((dbus_name, )))
1273
self.PropertiesChanged(_interface,
1296
dbus_value = transform_func(
1298
variant_level = variant_level)
1278
dbus_value = transform_func(type_func(value),
1299
1281
self.PropertyChanged(dbus.String(dbus_name),
1301
self.PropertiesChanged(
1303
dbus.Dictionary({ dbus.String(dbus_name):
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1306
1287
setattr(self, attrname, value)
1308
1289
return property(lambda self: getattr(self, attrname), setter)
1314
1295
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1315
1296
last_enabled = notifychangeproperty(datetime_to_dbus,
1317
checker = notifychangeproperty(
1318
dbus.Boolean, "CheckerRunning",
1319
type_func = lambda checker: checker is not None)
1298
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1299
type_func = lambda checker:
1300
checker is not None)
1320
1301
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1321
1302
"LastCheckedOK")
1322
1303
last_checker_status = notifychangeproperty(dbus.Int16,
1325
1306
datetime_to_dbus, "LastApprovalRequest")
1326
1307
approved_by_default = notifychangeproperty(dbus.Boolean,
1327
1308
"ApprovedByDefault")
1328
approval_delay = notifychangeproperty(
1329
dbus.UInt64, "ApprovalDelay",
1330
type_func = lambda td: td.total_seconds() * 1000)
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1312
lambda td: td.total_seconds()
1331
1314
approval_duration = notifychangeproperty(
1332
1315
dbus.UInt64, "ApprovalDuration",
1333
1316
type_func = lambda td: td.total_seconds() * 1000)
1334
1317
host = notifychangeproperty(dbus.String, "Host")
1335
timeout = notifychangeproperty(
1336
dbus.UInt64, "Timeout",
1337
type_func = lambda td: td.total_seconds() * 1000)
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1338
1321
extended_timeout = notifychangeproperty(
1339
1322
dbus.UInt64, "ExtendedTimeout",
1340
1323
type_func = lambda td: td.total_seconds() * 1000)
1341
interval = notifychangeproperty(
1342
dbus.UInt64, "Interval",
1343
type_func = lambda td: td.total_seconds() * 1000)
1324
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1344
1329
checker_command = notifychangeproperty(dbus.String, "Checker")
1345
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1346
1331
invalidate_only=True)
1484
1469
return dbus.Boolean(bool(self.approvals_pending))
1486
1471
# ApprovedByDefault - property
1487
@dbus_service_property(_interface,
1472
@dbus_service_property(_interface, signature="b",
1489
1473
access="readwrite")
1490
1474
def ApprovedByDefault_dbus_property(self, value=None):
1491
1475
if value is None: # get
1493
1477
self.approved_by_default = bool(value)
1495
1479
# ApprovalDelay - property
1496
@dbus_service_property(_interface,
1480
@dbus_service_property(_interface, signature="t",
1498
1481
access="readwrite")
1499
1482
def ApprovalDelay_dbus_property(self, value=None):
1500
1483
if value is None: # get
1503
1486
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1505
1488
# ApprovalDuration - property
1506
@dbus_service_property(_interface,
1489
@dbus_service_property(_interface, signature="t",
1508
1490
access="readwrite")
1509
1491
def ApprovalDuration_dbus_property(self, value=None):
1510
1492
if value is None: # get
1564
1543
return datetime_to_dbus(self.last_checked_ok)
1566
1545
# LastCheckerStatus - property
1567
@dbus_service_property(_interface, signature="n", access="read")
1546
@dbus_service_property(_interface, signature="n",
1568
1548
def LastCheckerStatus_dbus_property(self):
1569
1549
return dbus.Int16(self.last_checker_status)
1601
1580
gobject.source_remove(self.disable_initiator_tag)
1602
self.disable_initiator_tag = gobject.timeout_add(
1603
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))
1606
1586
# ExtendedTimeout - property
1607
@dbus_service_property(_interface,
1587
@dbus_service_property(_interface, signature="t",
1609
1588
access="readwrite")
1610
1589
def ExtendedTimeout_dbus_property(self, value=None):
1611
1590
if value is None: # get
1614
1593
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1616
1595
# Interval - property
1617
@dbus_service_property(_interface,
1596
@dbus_service_property(_interface, signature="t",
1619
1597
access="readwrite")
1620
1598
def Interval_dbus_property(self, value=None):
1621
1599
if value is None: # get
1626
1604
if self.enabled:
1627
1605
# Reschedule checker run
1628
1606
gobject.source_remove(self.checker_initiator_tag)
1629
self.checker_initiator_tag = gobject.timeout_add(
1630
value, self.start_checker)
1631
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
1633
1611
# Checker - property
1634
@dbus_service_property(_interface,
1612
@dbus_service_property(_interface, signature="s",
1636
1613
access="readwrite")
1637
1614
def Checker_dbus_property(self, value=None):
1638
1615
if value is None: # get
1657
1633
return self.dbus_object_path # is already a dbus.ObjectPath
1659
1635
# Secret = property
1660
@dbus_service_property(_interface,
1636
@dbus_service_property(_interface, signature="ay",
1637
access="write", byte_arrays=True)
1664
1638
def Secret_dbus_property(self, value):
1665
1639
self.secret = bytes(value)
1682
1656
if data[0] == 'data':
1684
1658
if data[0] == 'function':
1686
1659
def func(*args, **kwargs):
1687
1660
self._pipe.send(('funcall', name, args, kwargs))
1688
1661
return self._pipe.recv()[1]
1692
1664
def __setattr__(self, name, value):
1708
1680
logger.debug("Pipe FD: %d",
1709
1681
self.server.child_pipe.fileno())
1711
session = gnutls.connection.ClientSession(
1712
self.request, gnutls.connection .X509Credentials())
1683
session = (gnutls.connection
1684
.ClientSession(self.request,
1686
.X509Credentials()))
1714
1688
# Note: gnutls.connection.X509Credentials is really a
1715
1689
# generic GnuTLS certificate credentials object so long as
1724
1698
priority = self.server.gnutls_priority
1725
1699
if priority is None:
1726
1700
priority = "NORMAL"
1727
gnutls.library.functions.gnutls_priority_set_direct(
1728
session._c_object, priority, None)
1701
(gnutls.library.functions
1702
.gnutls_priority_set_direct(session._c_object,
1730
1705
# Start communication using the Mandos protocol
1731
1706
# Get protocol number
1826
1801
logger.warning("gnutls send failed",
1827
1802
exc_info=error)
1829
logger.debug("Sent: %d, remaining: %d", sent,
1830
len(client.secret) - (sent_size
1804
logger.debug("Sent: %d, remaining: %d",
1805
sent, len(client.secret)
1806
- (sent_size + sent))
1832
1807
sent_size += sent
1834
1809
logger.info("Sending secret to %s", client.name)
1851
1826
def peer_certificate(session):
1852
1827
"Return the peer's OpenPGP certificate as a bytestring"
1853
1828
# If not an OpenPGP certificate...
1854
if (gnutls.library.functions.gnutls_certificate_type_get(
1829
if (gnutls.library.functions
1830
.gnutls_certificate_type_get(session._c_object)
1856
1831
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1857
1832
# ...do the normal thing
1858
1833
return session.peer_certificate
1872
1847
def fingerprint(openpgp):
1873
1848
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1874
1849
# New GnuTLS "datum" with the OpenPGP public key
1875
datum = gnutls.library.types.gnutls_datum_t(
1876
ctypes.cast(ctypes.c_char_p(openpgp),
1877
ctypes.POINTER(ctypes.c_ubyte)),
1878
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))))
1879
1855
# New empty GnuTLS certificate
1880
1856
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1881
gnutls.library.functions.gnutls_openpgp_crt_init(
1857
(gnutls.library.functions
1858
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1883
1859
# Import the OpenPGP public key into the certificate
1884
gnutls.library.functions.gnutls_openpgp_crt_import(
1885
crt, ctypes.byref(datum),
1886
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))
1887
1864
# Verify the self signature in the key
1888
1865
crtverify = ctypes.c_uint()
1889
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
crt, 0, ctypes.byref(crtverify))
1866
(gnutls.library.functions
1867
.gnutls_openpgp_crt_verify_self(crt, 0,
1868
ctypes.byref(crtverify)))
1891
1869
if crtverify.value != 0:
1892
1870
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1893
raise gnutls.errors.CertificateSecurityError(
1871
raise (gnutls.errors.CertificateSecurityError
1895
1873
# New buffer for the fingerprint
1896
1874
buf = ctypes.create_string_buffer(20)
1897
1875
buf_len = ctypes.c_size_t()
1898
1876
# Get the fingerprint from the certificate into the buffer
1899
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
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)))
1901
1880
# Deinit the certificate
1902
1881
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1903
1882
# Convert the buffer to a Python bytestring
1954
1931
interface: None or a network interface name (string)
1955
1932
use_ipv6: Boolean; to use IPv6 or not
1958
1934
def __init__(self, server_address, RequestHandlerClass,
1935
interface=None, use_ipv6=True, socketfd=None):
1962
1936
"""If socketfd is set, use that file descriptor instead of
1963
1937
creating a new one with socket.socket().
2005
1979
self.interface)
2008
self.socket.setsockopt(
2009
socket.SOL_SOCKET, SO_BINDTODEVICE,
2010
(self.interface + "\0").encode("utf-8"))
1982
self.socket.setsockopt(socket.SOL_SOCKET,
1984
(self.interface + "\0")
2011
1986
except socket.error as error:
2012
1987
if error.errno == errno.EPERM:
2013
1988
logger.error("No permission to bind to"
2031
2006
self.server_address = (any_address,
2032
2007
self.server_address[1])
2033
2008
elif not self.server_address[1]:
2034
self.server_address = (self.server_address[0], 0)
2009
self.server_address = (self.server_address[0],
2035
2011
# if self.interface:
2036
2012
# self.server_address = (self.server_address[0],
2052
2028
Assumes a gobject.MainLoop event loop.
2055
2030
def __init__(self, server_address, RequestHandlerClass,
2059
gnutls_priority=None,
2031
interface=None, use_ipv6=True, clients=None,
2032
gnutls_priority=None, use_dbus=True, socketfd=None):
2062
2033
self.enabled = False
2063
2034
self.clients = clients
2064
2035
if self.clients is None:
2081
2051
def add_pipe(self, parent_pipe, proc):
2082
2052
# Call "handle_ipc" for both data and EOF events
2083
gobject.io_add_watch(
2084
parent_pipe.fileno(),
2085
gobject.IO_IN | gobject.IO_HUP,
2086
functools.partial(self.handle_ipc,
2087
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,
2090
def handle_ipc(self, source, condition,
2093
client_object=None):
2060
def handle_ipc(self, source, condition, parent_pipe=None,
2061
proc = None, client_object=None):
2094
2062
# error, or the other end of multiprocessing.Pipe has closed
2095
2063
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2096
2064
# Wait for other process to exit
2119
2087
parent_pipe.send(False)
2122
gobject.io_add_watch(
2123
parent_pipe.fileno(),
2124
gobject.IO_IN | gobject.IO_HUP,
2125
functools.partial(self.handle_ipc,
2126
parent_pipe = parent_pipe,
2128
client_object = client))
2090
gobject.io_add_watch(parent_pipe.fileno(),
2091
gobject.IO_IN | gobject.IO_HUP,
2092
functools.partial(self.handle_ipc,
2129
2098
parent_pipe.send(True)
2130
2099
# remove the old hook in favor of the new above hook on
2138
2107
parent_pipe.send(('data', getattr(client_object,
2139
2108
funcname)(*args,
2142
2111
if command == 'getattr':
2143
2112
attrname = request[1]
2144
2113
if callable(client_object.__getattribute__(attrname)):
2145
parent_pipe.send(('function', ))
2114
parent_pipe.send(('function',))
2148
'data', client_object.__getattribute__(attrname)))
2116
parent_pipe.send(('data', client_object
2117
.__getattribute__(attrname)))
2150
2119
if command == 'setattr':
2151
2120
attrname = request[1]
2192
2161
"followers")) # Tokens valid after
2194
Token = collections.namedtuple("Token", (
2195
"regexp", # To match token; if "value" is not None, must have
2196
# a "group" containing digits
2197
"value", # datetime.timedelta or None
2198
"followers")) # Tokens valid after this token
2199
2163
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2200
2164
# the "duration" ABNF definition in RFC 3339, Appendix A.
2201
2165
token_end = Token(re.compile(r"$"), None, frozenset())
2202
2166
token_second = Token(re.compile(r"(\d+)S"),
2203
2167
datetime.timedelta(seconds=1),
2204
frozenset((token_end, )))
2168
frozenset((token_end,)))
2205
2169
token_minute = Token(re.compile(r"(\d+)M"),
2206
2170
datetime.timedelta(minutes=1),
2207
2171
frozenset((token_second, token_end)))
2223
2187
frozenset((token_month, token_end)))
2224
2188
token_week = Token(re.compile(r"(\d+)W"),
2225
2189
datetime.timedelta(weeks=1),
2226
frozenset((token_end, )))
2190
frozenset((token_end,)))
2227
2191
token_duration = Token(re.compile(r"P"), None,
2228
2192
frozenset((token_year, token_month,
2229
2193
token_day, token_time,
2319
2284
# Close all standard open file descriptors
2320
2285
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2321
2286
if not stat.S_ISCHR(os.fstat(null).st_mode):
2322
raise OSError(errno.ENODEV,
2323
"{} not a character device"
2287
raise OSError(errno.ENODEV, "{} not a character device"
2324
2288
.format(os.devnull))
2325
2289
os.dup2(null, sys.stdin.fileno())
2326
2290
os.dup2(null, sys.stdout.fileno())
2403
2367
"statedir": "/var/lib/mandos",
2404
2368
"foreground": "False",
2405
2369
"zeroconf": "True",
2408
2372
# Parse config file for server-global settings
2409
2373
server_config = configparser.SafeConfigParser(server_defaults)
2410
2374
del server_defaults
2411
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2375
server_config.read(os.path.join(options.configdir,
2412
2377
# Convert the SafeConfigParser object to a dict
2413
2378
server_settings = server_config.defaults()
2414
2379
# Use the appropriate methods on the non-string config options
2432
2397
# Override the settings from the config file with command line
2433
2398
# options, if set.
2434
2399
for option in ("interface", "address", "port", "debug",
2435
"priority", "servicename", "configdir", "use_dbus",
2436
"use_ipv6", "debuglevel", "restore", "statedir",
2437
"socket", "foreground", "zeroconf"):
2400
"priority", "servicename", "configdir",
2401
"use_dbus", "use_ipv6", "debuglevel", "restore",
2402
"statedir", "socket", "foreground", "zeroconf"):
2438
2403
value = getattr(options, option)
2439
2404
if value is not None:
2440
2405
server_settings[option] = value
2456
2421
##################################################################
2458
if (not server_settings["zeroconf"]
2459
and not (server_settings["port"]
2460
or server_settings["socket"] != "")):
2461
parser.error("Needs port or socket to work without Zeroconf")
2423
if (not server_settings["zeroconf"] and
2424
not (server_settings["port"]
2425
or server_settings["socket"] != "")):
2426
parser.error("Needs port or socket to work without"
2463
2429
# For convenience
2464
2430
debug = server_settings["debug"]
2480
2446
initlogger(debug, level)
2482
2448
if server_settings["servicename"] != "Mandos":
2483
syslogger.setFormatter(
2484
logging.Formatter('Mandos ({}) [%(process)d]:'
2485
' %(levelname)s: %(message)s'.format(
2486
server_settings["servicename"])))
2449
syslogger.setFormatter(logging.Formatter
2450
('Mandos ({}) [%(process)d]:'
2451
' %(levelname)s: %(message)s'
2452
.format(server_settings
2488
2455
# Parse config file with clients
2489
2456
client_config = configparser.SafeConfigParser(Client
2497
2464
socketfd = None
2498
2465
if server_settings["socket"] != "":
2499
2466
socketfd = server_settings["socket"]
2500
tcp_server = MandosServer(
2501
(server_settings["address"], server_settings["port"]),
2503
interface=(server_settings["interface"] or None),
2505
gnutls_priority=server_settings["priority"],
2467
tcp_server = MandosServer((server_settings["address"],
2468
server_settings["port"]),
2470
interface=(server_settings["interface"]
2474
server_settings["priority"],
2508
2477
if not foreground:
2509
2478
pidfilename = "/run/mandos.pid"
2510
2479
if not os.path.isdir("/run/."):
2511
2480
pidfilename = "/var/run/mandos.pid"
2514
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2483
pidfile = open(pidfilename, "w")
2515
2484
except IOError as e:
2516
2485
logger.error("Could not open file %r", pidfilename,
2544
2513
def debug_gnutls(level, string):
2545
2514
logger.debug("GnuTLS: %s", string[:-1])
2547
gnutls.library.functions.gnutls_global_set_log_function(
2516
(gnutls.library.functions
2517
.gnutls_global_set_log_function(debug_gnutls))
2550
2519
# Redirect stdin so all checkers get /dev/null
2551
2520
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2573
2542
bus_name = dbus.service.BusName("se.recompile.Mandos",
2576
old_bus_name = dbus.service.BusName(
2577
"se.bsnet.fukt.Mandos", bus,
2579
except dbus.exceptions.DBusException as e:
2543
bus, do_not_queue=True)
2544
old_bus_name = (dbus.service.BusName
2545
("se.bsnet.fukt.Mandos", bus,
2547
except dbus.exceptions.NameExistsException as e:
2580
2548
logger.error("Disabling D-Bus:", exc_info=e)
2581
2549
use_dbus = False
2582
2550
server_settings["use_dbus"] = False
2583
2551
tcp_server.use_dbus = False
2585
2553
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2586
service = AvahiServiceToSyslog(
2587
name = server_settings["servicename"],
2588
servicetype = "_mandos._tcp",
2589
protocol = protocol,
2554
service = AvahiServiceToSyslog(name =
2555
server_settings["servicename"],
2556
servicetype = "_mandos._tcp",
2557
protocol = protocol, bus = bus)
2591
2558
if server_settings["interface"]:
2592
service.interface = if_nametoindex(
2593
server_settings["interface"].encode("utf-8"))
2559
service.interface = (if_nametoindex
2560
(server_settings["interface"]
2595
2563
global multiprocessing_manager
2596
2564
multiprocessing_manager = multiprocessing.Manager()
2615
2583
if server_settings["restore"]:
2617
2585
with open(stored_state_path, "rb") as stored_state:
2618
clients_data, old_client_settings = pickle.load(
2586
clients_data, old_client_settings = (pickle.load
2620
2588
os.remove(stored_state_path)
2621
2589
except IOError as e:
2622
2590
if e.errno == errno.ENOENT:
2623
logger.warning("Could not load persistent state:"
2624
" {}".format(os.strerror(e.errno)))
2591
logger.warning("Could not load persistent state: {}"
2592
.format(os.strerror(e.errno)))
2626
2594
logger.critical("Could not load persistent state:",
2629
2597
except EOFError as e:
2630
2598
logger.warning("Could not load persistent state: "
2599
"EOFError:", exc_info=e)
2634
2601
with PGPEngine() as pgp:
2635
2602
for client_name, client in clients_data.items():
2664
2631
if not client["last_checked_ok"]:
2665
2632
logger.warning(
2666
2633
"disabling client {} - Client never "
2667
"performed a successful checker".format(
2634
"performed a successful checker"
2635
.format(client_name))
2669
2636
client["enabled"] = False
2670
2637
elif client["last_checker_status"] != 0:
2671
2638
logger.warning(
2672
2639
"disabling client {} - Client last"
2673
" checker failed with error code"
2676
client["last_checker_status"]))
2640
" checker failed with error code {}"
2641
.format(client_name,
2642
client["last_checker_status"]))
2677
2643
client["enabled"] = False
2679
client["expires"] = (
2680
datetime.datetime.utcnow()
2681
+ client["timeout"])
2645
client["expires"] = (datetime.datetime
2647
+ client["timeout"])
2682
2648
logger.debug("Last checker succeeded,"
2683
" keeping {} enabled".format(
2649
" keeping {} enabled"
2650
.format(client_name))
2686
client["secret"] = pgp.decrypt(
2687
client["encrypted_secret"],
2688
client_settings[client_name]["secret"])
2652
client["secret"] = (
2653
pgp.decrypt(client["encrypted_secret"],
2654
client_settings[client_name]
2689
2656
except PGPError:
2690
2657
# If decryption fails, we use secret from new settings
2691
logger.debug("Failed to decrypt {} old secret".format(
2693
client["secret"] = (client_settings[client_name]
2658
logger.debug("Failed to decrypt {} old secret"
2659
.format(client_name))
2660
client["secret"] = (
2661
client_settings[client_name]["secret"])
2696
2663
# Add/remove clients based on new changes made to config
2697
2664
for client_name in (set(old_client_settings)
2704
2671
# Create all client objects
2705
2672
for client_name, client in clients_data.items():
2706
2673
tcp_server.clients[client_name] = client_class(
2674
name = client_name, settings = client,
2709
2675
server_settings = server_settings)
2711
2677
if not tcp_server.clients:
2727
2693
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2731
@alternate_dbus_interfaces(
2732
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2696
@alternate_dbus_interfaces({"se.recompile.Mandos":
2697
"se.bsnet.fukt.Mandos"})
2733
2698
class MandosDBusService(DBusObjectWithProperties):
2734
2699
"""A D-Bus proxy object"""
2736
2700
def __init__(self):
2737
2701
dbus.service.Object.__init__(self, bus, "/")
2739
2702
_interface = "se.recompile.Mandos"
2741
2704
@dbus_interface_annotations(_interface)
2742
2705
def _foo(self):
2744
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2706
return { "org.freedesktop.DBus.Property"
2707
".EmitsChangedSignal":
2747
2710
@dbus.service.signal(_interface, signature="o")
2748
2711
def ClientAdded(self, objpath):
2818
2782
exclude = { "bus", "changedstate", "secret",
2819
2783
"checker", "server_settings" }
2820
for name, typ in inspect.getmembers(dbus.service
2784
for name, typ in (inspect.getmembers
2785
(dbus.service.Object)):
2822
2786
exclude.add(name)
2824
2788
client_dict["encrypted_secret"] = (client
2831
2795
del client_settings[client.name]["secret"]
2834
with tempfile.NamedTemporaryFile(
2838
dir=os.path.dirname(stored_state_path),
2839
delete=False) as stored_state:
2798
with (tempfile.NamedTemporaryFile
2799
(mode='wb', suffix=".pickle", prefix='clients-',
2800
dir=os.path.dirname(stored_state_path),
2801
delete=False)) as stored_state:
2840
2802
pickle.dump((clients, client_settings), stored_state)
2841
tempname = stored_state.name
2803
tempname=stored_state.name
2842
2804
os.rename(tempname, stored_state_path)
2843
2805
except (IOError, OSError) as e: