361
381
def server_state_changed(self, state, error=None):
362
382
"""Derived from the Avahi example code"""
363
383
logger.debug("Avahi server state change: %i", state)
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" }
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",
371
390
if state in bad_states:
372
391
if bad_states[state] is not None:
373
392
if error is None:
400
419
def rename(self, *args, **kwargs):
401
420
"""Add the new name to the syslog messages"""
402
421
ret = AvahiService.rename(self, *args, **kwargs)
403
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
405
' %(levelname)s: %(message)s'
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))
410
437
class Client(object):
411
438
"""A representation of a client host served by this server.
456
485
"fingerprint", "host", "interval",
457
486
"last_approval_request", "last_checked_ok",
458
487
"last_enabled", "name", "timeout")
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
"extended_timeout": "PT15M",
492
"checker": "fping -q -- %%(host)s",
494
"approval_delay": "PT0S",
495
"approval_duration": "PT1S",
496
"approved_by_default": "True",
471
501
def config_parser(config):
549
579
self.current_checker_command = None
550
580
self.approved = None
551
581
self.approvals_pending = 0
552
self.changedstate = (multiprocessing_manager
553
.Condition(multiprocessing_manager
555
self.client_structure = [attr for attr in
556
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()
557
586
if not attr.startswith("_")]
558
587
self.client_structure.append("client_structure")
560
for name, t in inspect.getmembers(type(self),
589
for name, t in inspect.getmembers(
590
type(self), lambda obj: isinstance(obj, property)):
564
591
if not name.startswith("_"):
565
592
self.client_structure.append(name)
608
635
# and every interval from then on.
609
636
if self.checker_initiator_tag is not None:
610
637
gobject.source_remove(self.checker_initiator_tag)
611
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
638
self.checker_initiator_tag = gobject.timeout_add(
639
int(self.interval.total_seconds() * 1000),
615
641
# Schedule a disable() when 'timeout' has passed
616
642
if self.disable_initiator_tag is not None:
617
643
gobject.source_remove(self.disable_initiator_tag)
618
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
644
self.disable_initiator_tag = gobject.timeout_add(
645
int(self.timeout.total_seconds() * 1000), self.disable)
622
646
# Also start a new checker *right now*.
623
647
self.start_checker()
625
def checker_callback(self, pid, condition, command):
649
def checker_callback(self, source, condition, connection,
626
651
"""The checker has completed, so take appropriate actions."""
627
652
self.checker_callback_tag = None
628
653
self.checker = None
629
if os.WIFEXITED(condition):
630
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
631
661
if self.last_checker_status == 0:
632
662
logger.info("Checker for %(name)s succeeded",
634
664
self.checked_ok()
636
logger.info("Checker for %(name)s failed",
666
logger.info("Checker for %(name)s failed", vars(self))
639
668
self.last_checker_status = -1
669
self.last_checker_signal = -returncode
640
670
logger.warning("Checker for %(name)s crashed?",
643
674
def checked_ok(self):
644
675
"""Assert that the client has been seen, alive and well."""
645
676
self.last_checked_ok = datetime.datetime.utcnow()
646
677
self.last_checker_status = 0
678
self.last_checker_signal = None
647
679
self.bump_timeout()
649
681
def bump_timeout(self, timeout=None):
676
707
# than 'timeout' for the client to be disabled, which is as it
679
# If a checker exists, make sure it is not a zombie
681
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
682
except AttributeError:
684
except OSError as error:
685
if error.errno != errno.ECHILD:
689
logger.warning("Checker was a zombie")
690
gobject.source_remove(self.checker_callback_tag)
691
self.checker_callback(pid, status,
692
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")
693
714
# Start a new checker if needed
694
715
if self.checker is None:
695
716
# Escape attributes for the shell
696
escaped_attrs = { attr:
697
re.escape(str(getattr(self, attr)))
698
for attr in self.runtime_expansions }
718
attr: re.escape(str(getattr(self, attr)))
719
for attr in self.runtime_expansions }
700
721
command = self.checker_command % escaped_attrs
701
722
except TypeError as error:
702
723
logger.error('Could not format string "%s"',
703
self.checker_command, exc_info=error)
704
return True # Try again later
724
self.checker_command,
726
return True # Try again later
705
727
self.current_checker_command = command
707
logger.info("Starting checker %r for %s",
709
# We don't need to redirect stdout and stderr, since
710
# in normal mode, that is already done by daemon(),
711
# and in debug mode we don't want to. (Stdin is
712
# always replaced by /dev/null.)
713
# The exception is when not debugging but nevertheless
714
# running in the foreground; use the previously
717
if (not self.server_settings["debug"]
718
and self.server_settings["foreground"]):
719
popen_args.update({"stdout": wnull,
721
self.checker = subprocess.Popen(command,
725
except OSError as error:
726
logger.error("Failed to start subprocess",
729
self.checker_callback_tag = (gobject.child_watch_add
731
self.checker_callback,
733
# The checker may have completed before the gobject
734
# watch was added. Check for this.
736
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
737
except OSError as error:
738
if error.errno == errno.ECHILD:
739
# This should never happen
740
logger.error("Child process vanished",
745
gobject.source_remove(self.checker_callback_tag)
746
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)
747
753
# Re-run this periodically if run by gobject.timeout_add
871
879
def _get_all_dbus_things(self, thing):
872
880
"""Returns a generator of (name, attribute) pairs
874
return ((getattr(athing.__get__(self), "_dbus_name",
882
return ((getattr(athing.__get__(self), "_dbus_name", name),
876
883
athing.__get__(self))
877
884
for cls in self.__class__.__mro__
878
885
for name, athing in
879
inspect.getmembers(cls,
880
self._is_dbus_thing(thing)))
886
inspect.getmembers(cls, self._is_dbus_thing(thing)))
882
888
def _get_dbus_property(self, interface_name, property_name):
883
889
"""Returns a bound method if one exists which is a D-Bus
884
890
property with the specified name and interface.
886
for cls in self.__class__.__mro__:
887
for name, value in (inspect.getmembers
889
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")):
890
895
if (value._dbus_name == property_name
891
896
and value._dbus_interface == interface_name):
892
897
return value.__get__(self)
894
899
# No such property
895
raise DBusPropertyNotFound(self.dbus_object_path + ":"
896
+ interface_name + "."
900
raise DBusPropertyNotFound("{}:{}.{}".format(
901
self.dbus_object_path, interface_name, property_name))
899
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
903
@dbus.service.method(dbus.PROPERTIES_IFACE,
900
905
out_signature="v")
901
906
def Get(self, interface_name, property_name):
902
907
"""Standard D-Bus property Get() method, see D-Bus standard.
1083
1089
# Ignore non-D-Bus attributes, and D-Bus attributes
1084
1090
# with the wrong interface name
1085
1091
if (not hasattr(attribute, "_dbus_interface")
1086
or not attribute._dbus_interface
1087
.startswith(orig_interface_name)):
1092
or not attribute._dbus_interface.startswith(
1093
orig_interface_name)):
1089
1095
# Create an alternate D-Bus interface name based on
1090
1096
# the current name
1091
alt_interface = (attribute._dbus_interface
1092
.replace(orig_interface_name,
1093
alt_interface_name))
1097
alt_interface = attribute._dbus_interface.replace(
1098
orig_interface_name, alt_interface_name)
1094
1099
interface_names.add(alt_interface)
1095
1100
# Is this a D-Bus signal?
1096
1101
if getattr(attribute, "_dbus_is_signal", False):
1097
# Extract the original non-method undecorated
1098
# function by black magic
1099
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(
1100
1106
zip(attribute.func_code.co_freevars,
1101
attribute.__closure__))["func"]
1107
attribute.__closure__))
1108
["func"].cell_contents)
1110
nonmethod_func = attribute
1103
1111
# Create a new, but exactly alike, function
1104
1112
# object, and decorate it to be a new D-Bus signal
1105
1113
# with the alternate D-Bus interface name
1106
new_function = (dbus.service.signal
1108
attribute._dbus_signature)
1109
(types.FunctionType(
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)))
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))
1115
1131
# Copy annotations, if any
1117
new_function._dbus_annotations = (
1118
dict(attribute._dbus_annotations))
1133
new_function._dbus_annotations = dict(
1134
attribute._dbus_annotations)
1119
1135
except AttributeError:
1121
1137
# Define a creator of a function to call both the
1141
1159
# object. Decorate it to be a new D-Bus method
1142
1160
# with the alternate D-Bus interface name. Add it
1143
1161
# to the class.
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)))
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)))
1154
1172
# Copy annotations, if any
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1174
attr[attrname]._dbus_annotations = dict(
1175
attribute._dbus_annotations)
1158
1176
except AttributeError:
1160
1178
# Is this a D-Bus property?
1163
1181
# object, and decorate it to be a new D-Bus
1164
1182
# property with the alternate D-Bus interface
1165
1183
# name. Add it to the class.
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)))
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)))
1179
1195
# Copy annotations, if any
1181
attr[attrname]._dbus_annotations = (
1182
dict(attribute._dbus_annotations))
1197
attr[attrname]._dbus_annotations = dict(
1198
attribute._dbus_annotations)
1183
1199
except AttributeError:
1185
1201
# Is this a D-Bus interface?
1188
1204
# object. Decorate it to be a new D-Bus interface
1189
1205
# with the alternate D-Bus interface name. Add it
1190
1206
# to the class.
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)))
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)))
1200
1215
# Deprecate all alternate interfaces
1201
1216
iname="_AlternateDBusNames_interface_annotation{}"
1202
1217
for interface_name in interface_names:
1203
1219
@dbus_interface_annotations(interface_name)
1204
1220
def func(self):
1205
1221
return { "org.freedesktop.DBus.Deprecated":
1207
1223
# Find an unused name
1208
1224
for aname in (iname.format(i)
1209
1225
for i in itertools.count()):
1244
1261
client_object_name = str(self.name).translate(
1245
1262
{ord("."): ord("_"),
1246
1263
ord("-"): ord("_")})
1247
self.dbus_object_path = (dbus.ObjectPath
1248
("/clients/" + client_object_name))
1264
self.dbus_object_path = dbus.ObjectPath(
1265
"/clients/" + client_object_name)
1249
1266
DBusObjectWithProperties.__init__(self, self.bus,
1250
1267
self.dbus_object_path)
1252
def notifychangeproperty(transform_func,
1253
dbus_name, type_func=lambda x: x,
1254
variant_level=1, invalidate_only=False,
1269
def notifychangeproperty(transform_func, dbus_name,
1270
type_func=lambda x: x,
1272
invalidate_only=False,
1255
1273
_interface=_interface):
1256
1274
""" Modify a variable so that it's a property which announces
1257
1275
its changes to DBus.
1264
1282
variant_level: D-Bus variant level. Default: 1
1266
1284
attrname = "_{}".format(dbus_name)
1267
1286
def setter(self, value):
1268
1287
if hasattr(self, "dbus_object_path"):
1269
1288
if (not hasattr(self, attrname) or
1270
1289
type_func(getattr(self, attrname, None))
1271
1290
!= type_func(value)):
1272
1291
if invalidate_only:
1273
self.PropertiesChanged(_interface,
1292
self.PropertiesChanged(
1293
_interface, dbus.Dictionary(),
1294
dbus.Array((dbus_name, )))
1278
dbus_value = transform_func(type_func(value),
1296
dbus_value = transform_func(
1298
variant_level = variant_level)
1281
1299
self.PropertyChanged(dbus.String(dbus_name),
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1301
self.PropertiesChanged(
1303
dbus.Dictionary({ dbus.String(dbus_name):
1287
1306
setattr(self, attrname, value)
1289
1308
return property(lambda self: getattr(self, attrname), setter)
1295
1314
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1296
1315
last_enabled = notifychangeproperty(datetime_to_dbus,
1298
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1299
type_func = lambda checker:
1300
checker is not None)
1317
checker = notifychangeproperty(
1318
dbus.Boolean, "CheckerRunning",
1319
type_func = lambda checker: checker is not None)
1301
1320
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1302
1321
"LastCheckedOK")
1303
1322
last_checker_status = notifychangeproperty(dbus.Int16,
1306
1325
datetime_to_dbus, "LastApprovalRequest")
1307
1326
approved_by_default = notifychangeproperty(dbus.Boolean,
1308
1327
"ApprovedByDefault")
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1312
lambda td: td.total_seconds()
1328
approval_delay = notifychangeproperty(
1329
dbus.UInt64, "ApprovalDelay",
1330
type_func = lambda td: td.total_seconds() * 1000)
1314
1331
approval_duration = notifychangeproperty(
1315
1332
dbus.UInt64, "ApprovalDuration",
1316
1333
type_func = lambda td: td.total_seconds() * 1000)
1317
1334
host = notifychangeproperty(dbus.String, "Host")
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1335
timeout = notifychangeproperty(
1336
dbus.UInt64, "Timeout",
1337
type_func = lambda td: td.total_seconds() * 1000)
1321
1338
extended_timeout = notifychangeproperty(
1322
1339
dbus.UInt64, "ExtendedTimeout",
1323
1340
type_func = lambda td: td.total_seconds() * 1000)
1324
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1341
interval = notifychangeproperty(
1342
dbus.UInt64, "Interval",
1343
type_func = lambda td: td.total_seconds() * 1000)
1329
1344
checker_command = notifychangeproperty(dbus.String, "Checker")
1330
1345
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
1346
invalidate_only=True)
1341
1356
DBusObjectWithProperties.__del__(self, *args, **kwargs)
1342
1357
Client.__del__(self, *args, **kwargs)
1344
def checker_callback(self, pid, condition, command,
1346
self.checker_callback_tag = None
1348
if os.WIFEXITED(condition):
1349
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
1350
1366
# Emit D-Bus signal
1351
1367
self.CheckerCompleted(dbus.Int16(exitstatus),
1352
dbus.Int64(condition),
1353
1369
dbus.String(command))
1355
1371
# Emit D-Bus signal
1356
1372
self.CheckerCompleted(dbus.Int16(-1),
1357
dbus.Int64(condition),
1374
self.last_checker_signal),
1358
1375
dbus.String(command))
1360
return Client.checker_callback(self, pid, condition, command,
1363
1378
def start_checker(self, *args, **kwargs):
1364
1379
old_checker_pid = getattr(self.checker, "pid", None)
1604
1626
if self.enabled:
1605
1627
# Reschedule checker run
1606
1628
gobject.source_remove(self.checker_initiator_tag)
1607
self.checker_initiator_tag = (gobject.timeout_add
1608
(value, self.start_checker))
1609
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
1611
1633
# Checker - property
1612
@dbus_service_property(_interface, signature="s",
1634
@dbus_service_property(_interface,
1613
1636
access="readwrite")
1614
1637
def Checker_dbus_property(self, value=None):
1615
1638
if value is None: # get
1847
1872
def fingerprint(openpgp):
1848
1873
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1849
1874
# New GnuTLS "datum" with the OpenPGP public key
1850
datum = (gnutls.library.types
1851
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1854
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)))
1855
1879
# New empty GnuTLS certificate
1856
1880
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1857
(gnutls.library.functions
1858
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1881
gnutls.library.functions.gnutls_openpgp_crt_init(
1859
1883
# Import the OpenPGP public key into the certificate
1860
(gnutls.library.functions
1861
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1862
gnutls.library.constants
1863
.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)
1864
1887
# Verify the self signature in the key
1865
1888
crtverify = ctypes.c_uint()
1866
(gnutls.library.functions
1867
.gnutls_openpgp_crt_verify_self(crt, 0,
1868
ctypes.byref(crtverify)))
1889
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
crt, 0, ctypes.byref(crtverify))
1869
1891
if crtverify.value != 0:
1870
1892
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1871
raise (gnutls.errors.CertificateSecurityError
1893
raise gnutls.errors.CertificateSecurityError(
1873
1895
# New buffer for the fingerprint
1874
1896
buf = ctypes.create_string_buffer(20)
1875
1897
buf_len = ctypes.c_size_t()
1876
1898
# Get the fingerprint from the certificate into the buffer
1877
(gnutls.library.functions
1878
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1879
ctypes.byref(buf_len)))
1899
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1880
1901
# Deinit the certificate
1881
1902
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1882
1903
# Convert the buffer to a Python bytestring
2051
2081
def add_pipe(self, parent_pipe, proc):
2052
2082
# Call "handle_ipc" for both data and EOF events
2053
gobject.io_add_watch(parent_pipe.fileno(),
2054
gobject.IO_IN | gobject.IO_HUP,
2055
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,
2060
def handle_ipc(self, source, condition, parent_pipe=None,
2061
proc = None, client_object=None):
2090
def handle_ipc(self, source, condition,
2093
client_object=None):
2062
2094
# error, or the other end of multiprocessing.Pipe has closed
2063
2095
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2064
2096
# Wait for other process to exit
2151
2183
# avoid excessive use of external libraries.
2153
2185
# New type for defining tokens, syntax, and semantics all-in-one
2154
Token = collections.namedtuple("Token",
2155
("regexp", # To match token; if
2156
# "value" is not None,
2157
# must have a "group"
2159
"value", # datetime.timedelta or
2161
"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
2163
2191
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2164
2192
# the "duration" ABNF definition in RFC 3339, Appendix A.
2165
2193
token_end = Token(re.compile(r"$"), None, frozenset())
2166
2194
token_second = Token(re.compile(r"(\d+)S"),
2167
2195
datetime.timedelta(seconds=1),
2168
frozenset((token_end,)))
2196
frozenset((token_end, )))
2169
2197
token_minute = Token(re.compile(r"(\d+)M"),
2170
2198
datetime.timedelta(minutes=1),
2171
2199
frozenset((token_second, token_end)))
2397
2425
# Override the settings from the config file with command line
2398
2426
# options, if set.
2399
2427
for option in ("interface", "address", "port", "debug",
2400
"priority", "servicename", "configdir",
2401
"use_dbus", "use_ipv6", "debuglevel", "restore",
2402
"statedir", "socket", "foreground", "zeroconf"):
2428
"priority", "servicename", "configdir", "use_dbus",
2429
"use_ipv6", "debuglevel", "restore", "statedir",
2430
"socket", "foreground", "zeroconf"):
2403
2431
value = getattr(options, option)
2404
2432
if value is not None:
2405
2433
server_settings[option] = value
2464
2490
socketfd = None
2465
2491
if server_settings["socket"] != "":
2466
2492
socketfd = server_settings["socket"]
2467
tcp_server = MandosServer((server_settings["address"],
2468
server_settings["port"]),
2470
interface=(server_settings["interface"]
2474
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"],
2477
2501
if not foreground:
2478
2502
pidfilename = "/run/mandos.pid"
2479
2503
if not os.path.isdir("/run/."):
2480
2504
pidfilename = "/var/run/mandos.pid"
2483
pidfile = open(pidfilename, "w")
2507
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2484
2508
except IOError as e:
2485
2509
logger.error("Could not open file %r", pidfilename,
2542
2566
bus_name = dbus.service.BusName("se.recompile.Mandos",
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:
2569
old_bus_name = dbus.service.BusName(
2570
"se.bsnet.fukt.Mandos", bus,
2572
except dbus.exceptions.DBusException as e:
2548
2573
logger.error("Disabling D-Bus:", exc_info=e)
2549
2574
use_dbus = False
2550
2575
server_settings["use_dbus"] = False
2551
2576
tcp_server.use_dbus = False
2553
2578
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2554
service = AvahiServiceToSyslog(name =
2555
server_settings["servicename"],
2556
servicetype = "_mandos._tcp",
2557
protocol = protocol, bus = bus)
2579
service = AvahiServiceToSyslog(
2580
name = server_settings["servicename"],
2581
servicetype = "_mandos._tcp",
2582
protocol = protocol,
2558
2584
if server_settings["interface"]:
2559
service.interface = (if_nametoindex
2560
(server_settings["interface"]
2585
service.interface = if_nametoindex(
2586
server_settings["interface"].encode("utf-8"))
2563
2588
global multiprocessing_manager
2564
2589
multiprocessing_manager = multiprocessing.Manager()
2583
2608
if server_settings["restore"]:
2585
2610
with open(stored_state_path, "rb") as stored_state:
2586
clients_data, old_client_settings = (pickle.load
2611
clients_data, old_client_settings = pickle.load(
2588
2613
os.remove(stored_state_path)
2589
2614
except IOError as e:
2590
2615
if e.errno == errno.ENOENT:
2591
logger.warning("Could not load persistent state: {}"
2592
.format(os.strerror(e.errno)))
2616
logger.warning("Could not load persistent state:"
2617
" {}".format(os.strerror(e.errno)))
2594
2619
logger.critical("Could not load persistent state:",
2597
2622
except EOFError as e:
2598
2623
logger.warning("Could not load persistent state: "
2599
"EOFError:", exc_info=e)
2601
2627
with PGPEngine() as pgp:
2602
2628
for client_name, client in clients_data.items():
2631
2657
if not client["last_checked_ok"]:
2632
2658
logger.warning(
2633
2659
"disabling client {} - Client never "
2634
"performed a successful checker"
2635
.format(client_name))
2660
"performed a successful checker".format(
2636
2662
client["enabled"] = False
2637
2663
elif client["last_checker_status"] != 0:
2638
2664
logger.warning(
2639
2665
"disabling client {} - Client last"
2640
" checker failed with error code {}"
2641
.format(client_name,
2642
client["last_checker_status"]))
2666
" checker failed with error code"
2669
client["last_checker_status"]))
2643
2670
client["enabled"] = False
2645
client["expires"] = (datetime.datetime
2647
+ client["timeout"])
2672
client["expires"] = (
2673
datetime.datetime.utcnow()
2674
+ client["timeout"])
2648
2675
logger.debug("Last checker succeeded,"
2649
" keeping {} enabled"
2650
.format(client_name))
2676
" keeping {} enabled".format(
2652
client["secret"] = (
2653
pgp.decrypt(client["encrypted_secret"],
2654
client_settings[client_name]
2679
client["secret"] = pgp.decrypt(
2680
client["encrypted_secret"],
2681
client_settings[client_name]["secret"])
2656
2682
except PGPError:
2657
2683
# If decryption fails, we use secret from new settings
2658
logger.debug("Failed to decrypt {} old secret"
2659
.format(client_name))
2660
client["secret"] = (
2661
client_settings[client_name]["secret"])
2684
logger.debug("Failed to decrypt {} old secret".format(
2686
client["secret"] = (client_settings[client_name]
2663
2689
# Add/remove clients based on new changes made to config
2664
2690
for client_name in (set(old_client_settings)
2693
2720
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2696
@alternate_dbus_interfaces({"se.recompile.Mandos":
2697
"se.bsnet.fukt.Mandos"})
2724
@alternate_dbus_interfaces(
2725
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2698
2726
class MandosDBusService(DBusObjectWithProperties):
2699
2727
"""A D-Bus proxy object"""
2700
2729
def __init__(self):
2701
2730
dbus.service.Object.__init__(self, bus, "/")
2702
2732
_interface = "se.recompile.Mandos"
2704
2734
@dbus_interface_annotations(_interface)
2705
2735
def _foo(self):
2706
return { "org.freedesktop.DBus.Property"
2707
".EmitsChangedSignal":
2737
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2710
2740
@dbus.service.signal(_interface, signature="o")
2711
2741
def ClientAdded(self, objpath):
2795
2824
del client_settings[client.name]["secret"]
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:
2827
with tempfile.NamedTemporaryFile(
2831
dir=os.path.dirname(stored_state_path),
2832
delete=False) as stored_state:
2802
2833
pickle.dump((clients, client_settings), stored_state)
2803
tempname=stored_state.name
2834
tempname = stored_state.name
2804
2835
os.rename(tempname, stored_state_path)
2805
2836
except (IOError, OSError) as e: