276
297
self.entry_group_state_changed_match = None
299
def rename(self, remove=True):
279
300
"""Derived from the Avahi example code"""
280
301
if self.rename_count >= self.max_renames:
281
302
logger.critical("No suitable Zeroconf service name found"
282
303
" after %i retries, exiting.",
283
304
self.rename_count)
284
305
raise AvahiServiceError("Too many renames")
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
307
self.server.GetAlternativeServiceName(self.name))
308
self.rename_count += 1
287
309
logger.info("Changing Zeroconf service name to %r ...",
292
315
except dbus.exceptions.DBusException as error:
293
logger.critical("D-Bus Exception", exc_info=error)
296
self.rename_count += 1
316
if (error.get_dbus_name()
317
== "org.freedesktop.Avahi.CollisionError"):
318
logger.info("Local Zeroconf service name collision.")
319
return self.rename(remove=False)
321
logger.critical("D-Bus Exception", exc_info=error)
298
325
def remove(self):
299
326
"""Derived from the Avahi example code"""
355
381
def server_state_changed(self, state, error=None):
356
382
"""Derived from the Avahi example code"""
357
383
logger.debug("Avahi server state change: %i", state)
358
bad_states = { avahi.SERVER_INVALID:
359
"Zeroconf server invalid",
360
avahi.SERVER_REGISTERING: None,
361
avahi.SERVER_COLLISION:
362
"Zeroconf server name collision",
363
avahi.SERVER_FAILURE:
364
"Zeroconf server failure" }
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",
365
390
if state in bad_states:
366
391
if bad_states[state] is not None:
367
392
if error is None:
386
411
follow_name_owner_changes=True),
387
412
avahi.DBUS_INTERFACE_SERVER)
388
413
self.server.connect_to_signal("StateChanged",
389
self.server_state_changed)
414
self.server_state_changed)
390
415
self.server_state_changed(self.server.GetState())
393
418
class AvahiServiceToSyslog(AvahiService):
419
def rename(self, *args, **kwargs):
395
420
"""Add the new name to the syslog messages"""
396
ret = AvahiService.rename(self)
397
syslogger.setFormatter(logging.Formatter
398
('Mandos ({}) [%(process)d]:'
399
' %(levelname)s: %(message)s'
421
ret = AvahiService.rename(self, *args, **kwargs)
422
syslogger.setFormatter(logging.Formatter(
423
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
427
def call_pipe(connection, # : multiprocessing.Connection
428
func, *args, **kwargs):
429
"""This function is meant to be called by multiprocessing.Process
431
This function runs func(*args, **kwargs), and writes the resulting
432
return value on the provided multiprocessing.Connection.
434
connection.send(func(*args, **kwargs))
404
437
class Client(object):
405
438
"""A representation of a client host served by this server.
450
485
"fingerprint", "host", "interval",
451
486
"last_approval_request", "last_checked_ok",
452
487
"last_enabled", "name", "timeout")
453
client_defaults = { "timeout": "PT5M",
454
"extended_timeout": "PT15M",
456
"checker": "fping -q -- %%(host)s",
458
"approval_delay": "PT0S",
459
"approval_duration": "PT1S",
460
"approved_by_default": "True",
490
"extended_timeout": "PT15M",
492
"checker": "fping -q -- %%(host)s",
494
"approval_delay": "PT0S",
495
"approval_duration": "PT1S",
496
"approved_by_default": "True",
465
501
def config_parser(config):
543
579
self.current_checker_command = None
544
580
self.approved = None
545
581
self.approvals_pending = 0
546
self.changedstate = (multiprocessing_manager
547
.Condition(multiprocessing_manager
549
self.client_structure = [attr for attr in
550
self.__dict__.iterkeys()
582
self.changedstate = multiprocessing_manager.Condition(
583
multiprocessing_manager.Lock())
584
self.client_structure = [attr
585
for attr in self.__dict__.iterkeys()
551
586
if not attr.startswith("_")]
552
587
self.client_structure.append("client_structure")
554
for name, t in inspect.getmembers(type(self),
589
for name, t in inspect.getmembers(
590
type(self), lambda obj: isinstance(obj, property)):
558
591
if not name.startswith("_"):
559
592
self.client_structure.append(name)
602
635
# and every interval from then on.
603
636
if self.checker_initiator_tag is not None:
604
637
gobject.source_remove(self.checker_initiator_tag)
605
self.checker_initiator_tag = (gobject.timeout_add
607
.total_seconds() * 1000),
638
self.checker_initiator_tag = gobject.timeout_add(
639
int(self.interval.total_seconds() * 1000),
609
641
# Schedule a disable() when 'timeout' has passed
610
642
if self.disable_initiator_tag is not None:
611
643
gobject.source_remove(self.disable_initiator_tag)
612
self.disable_initiator_tag = (gobject.timeout_add
614
.total_seconds() * 1000),
644
self.disable_initiator_tag = gobject.timeout_add(
645
int(self.timeout.total_seconds() * 1000), self.disable)
616
646
# Also start a new checker *right now*.
617
647
self.start_checker()
619
def checker_callback(self, pid, condition, command):
649
def checker_callback(self, source, condition, connection,
620
651
"""The checker has completed, so take appropriate actions."""
621
652
self.checker_callback_tag = None
622
653
self.checker = None
623
if os.WIFEXITED(condition):
624
self.last_checker_status = os.WEXITSTATUS(condition)
654
# Read return code from connection (see call_pipe)
655
returncode = connection.recv()
659
self.last_checker_status = returncode
660
self.last_checker_signal = None
625
661
if self.last_checker_status == 0:
626
662
logger.info("Checker for %(name)s succeeded",
628
664
self.checked_ok()
630
logger.info("Checker for %(name)s failed",
666
logger.info("Checker for %(name)s failed", vars(self))
633
668
self.last_checker_status = -1
669
self.last_checker_signal = -returncode
634
670
logger.warning("Checker for %(name)s crashed?",
637
674
def checked_ok(self):
638
675
"""Assert that the client has been seen, alive and well."""
639
676
self.last_checked_ok = datetime.datetime.utcnow()
640
677
self.last_checker_status = 0
678
self.last_checker_signal = None
641
679
self.bump_timeout()
643
681
def bump_timeout(self, timeout=None):
670
707
# than 'timeout' for the client to be disabled, which is as it
673
# If a checker exists, make sure it is not a zombie
675
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
676
except AttributeError:
678
except OSError as error:
679
if error.errno != errno.ECHILD:
683
logger.warning("Checker was a zombie")
684
gobject.source_remove(self.checker_callback_tag)
685
self.checker_callback(pid, status,
686
self.current_checker_command)
710
if self.checker is not None and not self.checker.is_alive():
711
logger.warning("Checker was not alive; joining")
687
714
# Start a new checker if needed
688
715
if self.checker is None:
689
716
# Escape attributes for the shell
690
escaped_attrs = { attr:
691
re.escape(str(getattr(self, attr)))
692
for attr in self.runtime_expansions }
718
attr: re.escape(str(getattr(self, attr)))
719
for attr in self.runtime_expansions }
694
721
command = self.checker_command % escaped_attrs
695
722
except TypeError as error:
696
723
logger.error('Could not format string "%s"',
697
self.checker_command, exc_info=error)
698
return True # Try again later
724
self.checker_command,
726
return True # Try again later
699
727
self.current_checker_command = command
701
logger.info("Starting checker %r for %s",
703
# We don't need to redirect stdout and stderr, since
704
# in normal mode, that is already done by daemon(),
705
# and in debug mode we don't want to. (Stdin is
706
# always replaced by /dev/null.)
707
# The exception is when not debugging but nevertheless
708
# running in the foreground; use the previously
711
if (not self.server_settings["debug"]
712
and self.server_settings["foreground"]):
713
popen_args.update({"stdout": wnull,
715
self.checker = subprocess.Popen(command,
719
except OSError as error:
720
logger.error("Failed to start subprocess",
723
self.checker_callback_tag = (gobject.child_watch_add
725
self.checker_callback,
727
# The checker may have completed before the gobject
728
# watch was added. Check for this.
730
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
731
except OSError as error:
732
if error.errno == errno.ECHILD:
733
# This should never happen
734
logger.error("Child process vanished",
739
gobject.source_remove(self.checker_callback_tag)
740
self.checker_callback(pid, status, command)
728
logger.info("Starting checker %r for %s", command,
730
# We don't need to redirect stdout and stderr, since
731
# in normal mode, that is already done by daemon(),
732
# and in debug mode we don't want to. (Stdin is
733
# always replaced by /dev/null.)
734
# The exception is when not debugging but nevertheless
735
# running in the foreground; use the previously
737
popen_args = { "close_fds": True,
740
if (not self.server_settings["debug"]
741
and self.server_settings["foreground"]):
742
popen_args.update({"stdout": wnull,
744
pipe = multiprocessing.Pipe(duplex = False)
745
self.checker = multiprocessing.Process(
747
args = (pipe[1], subprocess.call, command),
750
self.checker_callback_tag = gobject.io_add_watch(
751
pipe[0].fileno(), gobject.IO_IN,
752
self.checker_callback, pipe[0], command)
741
753
# Re-run this periodically if run by gobject.timeout_add
813
824
"""Decorator to annotate D-Bus methods, signals or properties
827
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
828
"org.freedesktop.DBus.Property."
829
"EmitsChangedSignal": "false"})
816
830
@dbus_service_property("org.example.Interface", signature="b",
818
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
819
"org.freedesktop.DBus.Property."
820
"EmitsChangedSignal": "false"})
821
832
def Property_dbus_property(self):
822
833
return dbus.Boolean(False)
824
836
def decorator(func):
825
837
func._dbus_annotations = annotations
865
879
def _get_all_dbus_things(self, thing):
866
880
"""Returns a generator of (name, attribute) pairs
868
return ((getattr(athing.__get__(self), "_dbus_name",
882
return ((getattr(athing.__get__(self), "_dbus_name", name),
870
883
athing.__get__(self))
871
884
for cls in self.__class__.__mro__
872
885
for name, athing in
873
inspect.getmembers(cls,
874
self._is_dbus_thing(thing)))
886
inspect.getmembers(cls, self._is_dbus_thing(thing)))
876
888
def _get_dbus_property(self, interface_name, property_name):
877
889
"""Returns a bound method if one exists which is a D-Bus
878
890
property with the specified name and interface.
880
for cls in self.__class__.__mro__:
881
for name, value in (inspect.getmembers
883
self._is_dbus_thing("property"))):
892
for cls in self.__class__.__mro__:
893
for name, value in inspect.getmembers(
894
cls, self._is_dbus_thing("property")):
884
895
if (value._dbus_name == property_name
885
896
and value._dbus_interface == interface_name):
886
897
return value.__get__(self)
888
899
# No such property
889
raise DBusPropertyNotFound(self.dbus_object_path + ":"
890
+ interface_name + "."
900
raise DBusPropertyNotFound("{}:{}.{}".format(
901
self.dbus_object_path, interface_name, property_name))
893
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
903
@dbus.service.method(dbus.PROPERTIES_IFACE,
894
905
out_signature="v")
895
906
def Get(self, interface_name, property_name):
896
907
"""Standard D-Bus property Get() method, see D-Bus standard.
942
954
if not hasattr(value, "variant_level"):
943
955
properties[name] = value
945
properties[name] = type(value)(value, variant_level=
946
value.variant_level+1)
957
properties[name] = type(value)(
958
value, variant_level = value.variant_level + 1)
947
959
return dbus.Dictionary(properties, signature="sv")
961
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
962
def PropertiesChanged(self, interface_name, changed_properties,
963
invalidated_properties):
964
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
949
969
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
950
970
out_signature="s",
951
971
path_keyword='object_path',
1069
1089
# Ignore non-D-Bus attributes, and D-Bus attributes
1070
1090
# with the wrong interface name
1071
1091
if (not hasattr(attribute, "_dbus_interface")
1072
or not attribute._dbus_interface
1073
.startswith(orig_interface_name)):
1092
or not attribute._dbus_interface.startswith(
1093
orig_interface_name)):
1075
1095
# Create an alternate D-Bus interface name based on
1076
1096
# the current name
1077
alt_interface = (attribute._dbus_interface
1078
.replace(orig_interface_name,
1079
alt_interface_name))
1097
alt_interface = attribute._dbus_interface.replace(
1098
orig_interface_name, alt_interface_name)
1080
1099
interface_names.add(alt_interface)
1081
1100
# Is this a D-Bus signal?
1082
1101
if getattr(attribute, "_dbus_is_signal", False):
1083
# Extract the original non-method undecorated
1084
# function by black magic
1085
nonmethod_func = (dict(
1102
if sys.version_info.major == 2:
1103
# Extract the original non-method undecorated
1104
# function by black magic
1105
nonmethod_func = (dict(
1086
1106
zip(attribute.func_code.co_freevars,
1087
attribute.__closure__))["func"]
1107
attribute.__closure__))
1108
["func"].cell_contents)
1110
nonmethod_func = attribute
1089
1111
# Create a new, but exactly alike, function
1090
1112
# object, and decorate it to be a new D-Bus signal
1091
1113
# with the alternate D-Bus interface name
1092
new_function = (dbus.service.signal
1094
attribute._dbus_signature)
1095
(types.FunctionType(
1096
nonmethod_func.func_code,
1097
nonmethod_func.func_globals,
1098
nonmethod_func.func_name,
1099
nonmethod_func.func_defaults,
1100
nonmethod_func.func_closure)))
1114
if sys.version_info.major == 2:
1115
new_function = types.FunctionType(
1116
nonmethod_func.func_code,
1117
nonmethod_func.func_globals,
1118
nonmethod_func.func_name,
1119
nonmethod_func.func_defaults,
1120
nonmethod_func.func_closure)
1122
new_function = types.FunctionType(
1123
nonmethod_func.__code__,
1124
nonmethod_func.__globals__,
1125
nonmethod_func.__name__,
1126
nonmethod_func.__defaults__,
1127
nonmethod_func.__closure__)
1128
new_function = (dbus.service.signal(
1130
attribute._dbus_signature)(new_function))
1101
1131
# Copy annotations, if any
1103
new_function._dbus_annotations = (
1104
dict(attribute._dbus_annotations))
1133
new_function._dbus_annotations = dict(
1134
attribute._dbus_annotations)
1105
1135
except AttributeError:
1107
1137
# Define a creator of a function to call both the
1127
1159
# object. Decorate it to be a new D-Bus method
1128
1160
# with the alternate D-Bus interface name. Add it
1129
1161
# to the class.
1130
attr[attrname] = (dbus.service.method
1132
attribute._dbus_in_signature,
1133
attribute._dbus_out_signature)
1135
(attribute.func_code,
1136
attribute.func_globals,
1137
attribute.func_name,
1138
attribute.func_defaults,
1139
attribute.func_closure)))
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)))
1140
1172
# Copy annotations, if any
1142
attr[attrname]._dbus_annotations = (
1143
dict(attribute._dbus_annotations))
1174
attr[attrname]._dbus_annotations = dict(
1175
attribute._dbus_annotations)
1144
1176
except AttributeError:
1146
1178
# Is this a D-Bus property?
1149
1181
# object, and decorate it to be a new D-Bus
1150
1182
# property with the alternate D-Bus interface
1151
1183
# name. Add it to the class.
1152
attr[attrname] = (dbus_service_property
1154
attribute._dbus_signature,
1155
attribute._dbus_access,
1157
._dbus_get_args_options
1160
(attribute.func_code,
1161
attribute.func_globals,
1162
attribute.func_name,
1163
attribute.func_defaults,
1164
attribute.func_closure)))
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)))
1165
1195
# Copy annotations, if any
1167
attr[attrname]._dbus_annotations = (
1168
dict(attribute._dbus_annotations))
1197
attr[attrname]._dbus_annotations = dict(
1198
attribute._dbus_annotations)
1169
1199
except AttributeError:
1171
1201
# Is this a D-Bus interface?
1174
1204
# object. Decorate it to be a new D-Bus interface
1175
1205
# with the alternate D-Bus interface name. Add it
1176
1206
# to the class.
1177
attr[attrname] = (dbus_interface_annotations
1180
(attribute.func_code,
1181
attribute.func_globals,
1182
attribute.func_name,
1183
attribute.func_defaults,
1184
attribute.func_closure)))
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)))
1186
1215
# Deprecate all alternate interfaces
1187
1216
iname="_AlternateDBusNames_interface_annotation{}"
1188
1217
for interface_name in interface_names:
1189
1219
@dbus_interface_annotations(interface_name)
1190
1220
def func(self):
1191
1221
return { "org.freedesktop.DBus.Deprecated":
1193
1223
# Find an unused name
1194
1224
for aname in (iname.format(i)
1195
1225
for i in itertools.count()):
1228
1261
client_object_name = str(self.name).translate(
1229
1262
{ord("."): ord("_"),
1230
1263
ord("-"): ord("_")})
1231
self.dbus_object_path = (dbus.ObjectPath
1232
("/clients/" + client_object_name))
1264
self.dbus_object_path = dbus.ObjectPath(
1265
"/clients/" + client_object_name)
1233
1266
DBusObjectWithProperties.__init__(self, self.bus,
1234
1267
self.dbus_object_path)
1236
def notifychangeproperty(transform_func,
1237
dbus_name, type_func=lambda x: x,
1269
def notifychangeproperty(transform_func, dbus_name,
1270
type_func=lambda x: x,
1272
invalidate_only=False,
1273
_interface=_interface):
1239
1274
""" Modify a variable so that it's a property which announces
1240
1275
its changes to DBus.
1247
1282
variant_level: D-Bus variant level. Default: 1
1249
1284
attrname = "_{}".format(dbus_name)
1250
1286
def setter(self, value):
1251
1287
if hasattr(self, "dbus_object_path"):
1252
1288
if (not hasattr(self, attrname) or
1253
1289
type_func(getattr(self, attrname, None))
1254
1290
!= type_func(value)):
1255
dbus_value = transform_func(type_func(value),
1258
self.PropertyChanged(dbus.String(dbus_name),
1292
self.PropertiesChanged(
1293
_interface, dbus.Dictionary(),
1294
dbus.Array((dbus_name, )))
1296
dbus_value = transform_func(
1298
variant_level = variant_level)
1299
self.PropertyChanged(dbus.String(dbus_name),
1301
self.PropertiesChanged(
1303
dbus.Dictionary({ dbus.String(dbus_name):
1260
1306
setattr(self, attrname, value)
1262
1308
return property(lambda self: getattr(self, attrname), setter)
1268
1314
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1269
1315
last_enabled = notifychangeproperty(datetime_to_dbus,
1271
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1272
type_func = lambda checker:
1273
checker is not None)
1317
checker = notifychangeproperty(
1318
dbus.Boolean, "CheckerRunning",
1319
type_func = lambda checker: checker is not None)
1274
1320
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1275
1321
"LastCheckedOK")
1276
1322
last_checker_status = notifychangeproperty(dbus.Int16,
1279
1325
datetime_to_dbus, "LastApprovalRequest")
1280
1326
approved_by_default = notifychangeproperty(dbus.Boolean,
1281
1327
"ApprovedByDefault")
1282
approval_delay = notifychangeproperty(dbus.UInt64,
1285
lambda td: td.total_seconds()
1328
approval_delay = notifychangeproperty(
1329
dbus.UInt64, "ApprovalDelay",
1330
type_func = lambda td: td.total_seconds() * 1000)
1287
1331
approval_duration = notifychangeproperty(
1288
1332
dbus.UInt64, "ApprovalDuration",
1289
1333
type_func = lambda td: td.total_seconds() * 1000)
1290
1334
host = notifychangeproperty(dbus.String, "Host")
1291
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1292
type_func = lambda td:
1293
td.total_seconds() * 1000)
1335
timeout = notifychangeproperty(
1336
dbus.UInt64, "Timeout",
1337
type_func = lambda td: td.total_seconds() * 1000)
1294
1338
extended_timeout = notifychangeproperty(
1295
1339
dbus.UInt64, "ExtendedTimeout",
1296
1340
type_func = lambda td: td.total_seconds() * 1000)
1297
interval = notifychangeproperty(dbus.UInt64,
1300
lambda td: td.total_seconds()
1341
interval = notifychangeproperty(
1342
dbus.UInt64, "Interval",
1343
type_func = lambda td: td.total_seconds() * 1000)
1302
1344
checker_command = notifychangeproperty(dbus.String, "Checker")
1345
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1346
invalidate_only=True)
1304
1348
del notifychangeproperty
1312
1356
DBusObjectWithProperties.__del__(self, *args, **kwargs)
1313
1357
Client.__del__(self, *args, **kwargs)
1315
def checker_callback(self, pid, condition, command,
1317
self.checker_callback_tag = None
1319
if os.WIFEXITED(condition):
1320
exitstatus = os.WEXITSTATUS(condition)
1359
def checker_callback(self, source, condition,
1360
connection, command, *args, **kwargs):
1361
ret = Client.checker_callback(self, source, condition,
1362
connection, command, *args,
1364
exitstatus = self.last_checker_status
1321
1366
# Emit D-Bus signal
1322
1367
self.CheckerCompleted(dbus.Int16(exitstatus),
1323
dbus.Int64(condition),
1324
1369
dbus.String(command))
1326
1371
# Emit D-Bus signal
1327
1372
self.CheckerCompleted(dbus.Int16(-1),
1328
dbus.Int64(condition),
1374
self.last_checker_signal),
1329
1375
dbus.String(command))
1331
return Client.checker_callback(self, pid, condition, command,
1334
1378
def start_checker(self, *args, **kwargs):
1335
1379
old_checker_pid = getattr(self.checker, "pid", None)
1580
1626
if self.enabled:
1581
1627
# Reschedule checker run
1582
1628
gobject.source_remove(self.checker_initiator_tag)
1583
self.checker_initiator_tag = (gobject.timeout_add
1584
(value, self.start_checker))
1585
self.start_checker() # Start one now, too
1629
self.checker_initiator_tag = gobject.timeout_add(
1630
value, self.start_checker)
1631
self.start_checker() # Start one now, too
1587
1633
# Checker - property
1588
@dbus_service_property(_interface, signature="s",
1634
@dbus_service_property(_interface,
1589
1636
access="readwrite")
1590
1637
def Checker_dbus_property(self, value=None):
1591
1638
if value is None: # get
1823
1872
def fingerprint(openpgp):
1824
1873
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1825
1874
# New GnuTLS "datum" with the OpenPGP public key
1826
datum = (gnutls.library.types
1827
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1830
ctypes.c_uint(len(openpgp))))
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)))
1831
1879
# New empty GnuTLS certificate
1832
1880
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1833
(gnutls.library.functions
1834
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1881
gnutls.library.functions.gnutls_openpgp_crt_init(
1835
1883
# Import the OpenPGP public key into the certificate
1836
(gnutls.library.functions
1837
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1838
gnutls.library.constants
1839
.GNUTLS_OPENPGP_FMT_RAW))
1884
gnutls.library.functions.gnutls_openpgp_crt_import(
1885
crt, ctypes.byref(datum),
1886
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1840
1887
# Verify the self signature in the key
1841
1888
crtverify = ctypes.c_uint()
1842
(gnutls.library.functions
1843
.gnutls_openpgp_crt_verify_self(crt, 0,
1844
ctypes.byref(crtverify)))
1889
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
crt, 0, ctypes.byref(crtverify))
1845
1891
if crtverify.value != 0:
1846
1892
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1847
raise (gnutls.errors.CertificateSecurityError
1893
raise gnutls.errors.CertificateSecurityError(
1849
1895
# New buffer for the fingerprint
1850
1896
buf = ctypes.create_string_buffer(20)
1851
1897
buf_len = ctypes.c_size_t()
1852
1898
# Get the fingerprint from the certificate into the buffer
1853
(gnutls.library.functions
1854
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1855
ctypes.byref(buf_len)))
1899
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1856
1901
# Deinit the certificate
1857
1902
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1858
1903
# Convert the buffer to a Python bytestring
2027
2081
def add_pipe(self, parent_pipe, proc):
2028
2082
# Call "handle_ipc" for both data and EOF events
2029
gobject.io_add_watch(parent_pipe.fileno(),
2030
gobject.IO_IN | gobject.IO_HUP,
2031
functools.partial(self.handle_ipc,
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,
2036
def handle_ipc(self, source, condition, parent_pipe=None,
2037
proc = None, client_object=None):
2090
def handle_ipc(self, source, condition,
2093
client_object=None):
2038
2094
# error, or the other end of multiprocessing.Pipe has closed
2039
2095
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2040
2096
# Wait for other process to exit
2127
2183
# avoid excessive use of external libraries.
2129
2185
# New type for defining tokens, syntax, and semantics all-in-one
2130
Token = collections.namedtuple("Token",
2131
("regexp", # To match token; if
2132
# "value" is not None,
2133
# must have a "group"
2135
"value", # datetime.timedelta or
2137
"followers")) # Tokens valid after
2186
Token = collections.namedtuple("Token", (
2187
"regexp", # To match token; if "value" is not None, must have
2188
# a "group" containing digits
2189
"value", # datetime.timedelta or None
2190
"followers")) # Tokens valid after this token
2139
2191
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2140
2192
# the "duration" ABNF definition in RFC 3339, Appendix A.
2141
2193
token_end = Token(re.compile(r"$"), None, frozenset())
2142
2194
token_second = Token(re.compile(r"(\d+)S"),
2143
2195
datetime.timedelta(seconds=1),
2144
frozenset((token_end,)))
2196
frozenset((token_end, )))
2145
2197
token_minute = Token(re.compile(r"(\d+)M"),
2146
2198
datetime.timedelta(minutes=1),
2147
2199
frozenset((token_second, token_end)))
2372
2425
# Override the settings from the config file with command line
2373
2426
# options, if set.
2374
2427
for option in ("interface", "address", "port", "debug",
2375
"priority", "servicename", "configdir",
2376
"use_dbus", "use_ipv6", "debuglevel", "restore",
2377
"statedir", "socket", "foreground", "zeroconf"):
2428
"priority", "servicename", "configdir", "use_dbus",
2429
"use_ipv6", "debuglevel", "restore", "statedir",
2430
"socket", "foreground", "zeroconf"):
2378
2431
value = getattr(options, option)
2379
2432
if value is not None:
2380
2433
server_settings[option] = value
2439
2490
socketfd = None
2440
2491
if server_settings["socket"] != "":
2441
2492
socketfd = server_settings["socket"]
2442
tcp_server = MandosServer((server_settings["address"],
2443
server_settings["port"]),
2445
interface=(server_settings["interface"]
2449
server_settings["priority"],
2493
tcp_server = MandosServer(
2494
(server_settings["address"], server_settings["port"]),
2496
interface=(server_settings["interface"] or None),
2498
gnutls_priority=server_settings["priority"],
2452
2501
if not foreground:
2453
2502
pidfilename = "/run/mandos.pid"
2454
2503
if not os.path.isdir("/run/."):
2455
2504
pidfilename = "/var/run/mandos.pid"
2458
pidfile = open(pidfilename, "w")
2507
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2459
2508
except IOError as e:
2460
2509
logger.error("Could not open file %r", pidfilename,
2517
2566
bus_name = dbus.service.BusName("se.recompile.Mandos",
2518
bus, do_not_queue=True)
2519
old_bus_name = (dbus.service.BusName
2520
("se.bsnet.fukt.Mandos", bus,
2522
except dbus.exceptions.NameExistsException as e:
2569
old_bus_name = dbus.service.BusName(
2570
"se.bsnet.fukt.Mandos", bus,
2572
except dbus.exceptions.DBusException as e:
2523
2573
logger.error("Disabling D-Bus:", exc_info=e)
2524
2574
use_dbus = False
2525
2575
server_settings["use_dbus"] = False
2526
2576
tcp_server.use_dbus = False
2528
2578
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2529
service = AvahiServiceToSyslog(name =
2530
server_settings["servicename"],
2531
servicetype = "_mandos._tcp",
2532
protocol = protocol, bus = bus)
2579
service = AvahiServiceToSyslog(
2580
name = server_settings["servicename"],
2581
servicetype = "_mandos._tcp",
2582
protocol = protocol,
2533
2584
if server_settings["interface"]:
2534
service.interface = (if_nametoindex
2535
(server_settings["interface"]
2585
service.interface = if_nametoindex(
2586
server_settings["interface"].encode("utf-8"))
2538
2588
global multiprocessing_manager
2539
2589
multiprocessing_manager = multiprocessing.Manager()
2558
2608
if server_settings["restore"]:
2560
2610
with open(stored_state_path, "rb") as stored_state:
2561
clients_data, old_client_settings = (pickle.load
2611
clients_data, old_client_settings = pickle.load(
2563
2613
os.remove(stored_state_path)
2564
2614
except IOError as e:
2565
2615
if e.errno == errno.ENOENT:
2566
logger.warning("Could not load persistent state: {}"
2567
.format(os.strerror(e.errno)))
2616
logger.warning("Could not load persistent state:"
2617
" {}".format(os.strerror(e.errno)))
2569
2619
logger.critical("Could not load persistent state:",
2572
2622
except EOFError as e:
2573
2623
logger.warning("Could not load persistent state: "
2574
"EOFError:", exc_info=e)
2576
2627
with PGPEngine() as pgp:
2577
2628
for client_name, client in clients_data.items():
2606
2657
if not client["last_checked_ok"]:
2607
2658
logger.warning(
2608
2659
"disabling client {} - Client never "
2609
"performed a successful checker"
2610
.format(client_name))
2660
"performed a successful checker".format(
2611
2662
client["enabled"] = False
2612
2663
elif client["last_checker_status"] != 0:
2613
2664
logger.warning(
2614
2665
"disabling client {} - Client last"
2615
" checker failed with error code {}"
2616
.format(client_name,
2617
client["last_checker_status"]))
2666
" checker failed with error code"
2669
client["last_checker_status"]))
2618
2670
client["enabled"] = False
2620
client["expires"] = (datetime.datetime
2622
+ client["timeout"])
2672
client["expires"] = (
2673
datetime.datetime.utcnow()
2674
+ client["timeout"])
2623
2675
logger.debug("Last checker succeeded,"
2624
" keeping {} enabled"
2625
.format(client_name))
2676
" keeping {} enabled".format(
2627
client["secret"] = (
2628
pgp.decrypt(client["encrypted_secret"],
2629
client_settings[client_name]
2679
client["secret"] = pgp.decrypt(
2680
client["encrypted_secret"],
2681
client_settings[client_name]["secret"])
2631
2682
except PGPError:
2632
2683
# If decryption fails, we use secret from new settings
2633
logger.debug("Failed to decrypt {} old secret"
2634
.format(client_name))
2635
client["secret"] = (
2636
client_settings[client_name]["secret"])
2684
logger.debug("Failed to decrypt {} old secret".format(
2686
client["secret"] = (client_settings[client_name]
2638
2689
# Add/remove clients based on new changes made to config
2639
2690
for client_name in (set(old_client_settings)
2668
2720
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2671
@alternate_dbus_interfaces({"se.recompile.Mandos":
2672
"se.bsnet.fukt.Mandos"})
2724
@alternate_dbus_interfaces(
2725
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2673
2726
class MandosDBusService(DBusObjectWithProperties):
2674
2727
"""A D-Bus proxy object"""
2675
2729
def __init__(self):
2676
2730
dbus.service.Object.__init__(self, bus, "/")
2677
2732
_interface = "se.recompile.Mandos"
2679
2734
@dbus_interface_annotations(_interface)
2680
2735
def _foo(self):
2681
return { "org.freedesktop.DBus.Property"
2682
".EmitsChangedSignal":
2737
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2685
2740
@dbus.service.signal(_interface, signature="o")
2686
2741
def ClientAdded(self, objpath):
2770
2824
del client_settings[client.name]["secret"]
2773
with (tempfile.NamedTemporaryFile
2774
(mode='wb', suffix=".pickle", prefix='clients-',
2775
dir=os.path.dirname(stored_state_path),
2776
delete=False)) as stored_state:
2827
with tempfile.NamedTemporaryFile(
2831
dir=os.path.dirname(stored_state_path),
2832
delete=False) as stored_state:
2777
2833
pickle.dump((clients, client_settings), stored_state)
2778
tempname=stored_state.name
2834
tempname = stored_state.name
2779
2835
os.rename(tempname, stored_state_path)
2780
2836
except (IOError, OSError) as e: