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
430
def rename(self, *args, **kwargs):
401
431
"""Add the new name to the syslog messages"""
402
432
ret = AvahiService.rename(self, *args, **kwargs)
403
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
405
' %(levelname)s: %(message)s'
433
syslogger.setFormatter(logging.Formatter(
434
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
438
def call_pipe(connection, # : multiprocessing.Connection
439
func, *args, **kwargs):
440
"""This function is meant to be called by multiprocessing.Process
442
This function runs func(*args, **kwargs), and writes the resulting
443
return value on the provided multiprocessing.Connection.
445
connection.send(func(*args, **kwargs))
410
448
class Client(object):
411
449
"""A representation of a client host served by this server.
456
496
"fingerprint", "host", "interval",
457
497
"last_approval_request", "last_checked_ok",
458
498
"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",
501
"extended_timeout": "PT15M",
503
"checker": "fping -q -- %%(host)s",
505
"approval_delay": "PT0S",
506
"approval_duration": "PT1S",
507
"approved_by_default": "True",
471
512
def config_parser(config):
549
590
self.current_checker_command = None
550
591
self.approved = None
551
592
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()
593
self.changedstate = multiprocessing_manager.Condition(
594
multiprocessing_manager.Lock())
595
self.client_structure = [attr
596
for attr in self.__dict__.iterkeys()
557
597
if not attr.startswith("_")]
558
598
self.client_structure.append("client_structure")
560
for name, t in inspect.getmembers(type(self),
600
for name, t in inspect.getmembers(
601
type(self), lambda obj: isinstance(obj, property)):
564
602
if not name.startswith("_"):
565
603
self.client_structure.append(name)
608
646
# and every interval from then on.
609
647
if self.checker_initiator_tag is not None:
610
648
gobject.source_remove(self.checker_initiator_tag)
611
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
649
self.checker_initiator_tag = gobject.timeout_add(
650
int(self.interval.total_seconds() * 1000),
615
652
# Schedule a disable() when 'timeout' has passed
616
653
if self.disable_initiator_tag is not None:
617
654
gobject.source_remove(self.disable_initiator_tag)
618
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
655
self.disable_initiator_tag = gobject.timeout_add(
656
int(self.timeout.total_seconds() * 1000), self.disable)
622
657
# Also start a new checker *right now*.
623
658
self.start_checker()
625
def checker_callback(self, pid, condition, command):
660
def checker_callback(self, source, condition, connection,
626
662
"""The checker has completed, so take appropriate actions."""
627
663
self.checker_callback_tag = None
628
664
self.checker = None
629
if os.WIFEXITED(condition):
630
self.last_checker_status = os.WEXITSTATUS(condition)
665
# Read return code from connection (see call_pipe)
666
returncode = connection.recv()
670
self.last_checker_status = returncode
671
self.last_checker_signal = None
631
672
if self.last_checker_status == 0:
632
673
logger.info("Checker for %(name)s succeeded",
634
675
self.checked_ok()
636
logger.info("Checker for %(name)s failed",
677
logger.info("Checker for %(name)s failed", vars(self))
639
679
self.last_checker_status = -1
680
self.last_checker_signal = -returncode
640
681
logger.warning("Checker for %(name)s crashed?",
643
685
def checked_ok(self):
644
686
"""Assert that the client has been seen, alive and well."""
645
687
self.last_checked_ok = datetime.datetime.utcnow()
646
688
self.last_checker_status = 0
689
self.last_checker_signal = None
647
690
self.bump_timeout()
649
692
def bump_timeout(self, timeout=None):
676
718
# 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)
721
if self.checker is not None and not self.checker.is_alive():
722
logger.warning("Checker was not alive; joining")
693
725
# Start a new checker if needed
694
726
if self.checker is None:
695
727
# Escape attributes for the shell
696
escaped_attrs = { attr:
697
re.escape(str(getattr(self, attr)))
698
for attr in self.runtime_expansions }
729
attr: re.escape(str(getattr(self, attr)))
730
for attr in self.runtime_expansions }
700
732
command = self.checker_command % escaped_attrs
701
733
except TypeError as error:
702
734
logger.error('Could not format string "%s"',
703
self.checker_command, exc_info=error)
704
return True # Try again later
735
self.checker_command,
737
return True # Try again later
705
738
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)
739
logger.info("Starting checker %r for %s", command,
741
# We don't need to redirect stdout and stderr, since
742
# in normal mode, that is already done by daemon(),
743
# and in debug mode we don't want to. (Stdin is
744
# always replaced by /dev/null.)
745
# The exception is when not debugging but nevertheless
746
# running in the foreground; use the previously
748
popen_args = { "close_fds": True,
751
if (not self.server_settings["debug"]
752
and self.server_settings["foreground"]):
753
popen_args.update({"stdout": wnull,
755
pipe = multiprocessing.Pipe(duplex = False)
756
self.checker = multiprocessing.Process(
758
args = (pipe[1], subprocess.call, command),
761
self.checker_callback_tag = gobject.io_add_watch(
762
pipe[0].fileno(), gobject.IO_IN,
763
self.checker_callback, pipe[0], command)
747
764
# Re-run this periodically if run by gobject.timeout_add
871
890
def _get_all_dbus_things(self, thing):
872
891
"""Returns a generator of (name, attribute) pairs
874
return ((getattr(athing.__get__(self), "_dbus_name",
893
return ((getattr(athing.__get__(self), "_dbus_name", name),
876
894
athing.__get__(self))
877
895
for cls in self.__class__.__mro__
878
896
for name, athing in
879
inspect.getmembers(cls,
880
self._is_dbus_thing(thing)))
897
inspect.getmembers(cls, self._is_dbus_thing(thing)))
882
899
def _get_dbus_property(self, interface_name, property_name):
883
900
"""Returns a bound method if one exists which is a D-Bus
884
901
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"))):
903
for cls in self.__class__.__mro__:
904
for name, value in inspect.getmembers(
905
cls, self._is_dbus_thing("property")):
890
906
if (value._dbus_name == property_name
891
907
and value._dbus_interface == interface_name):
892
908
return value.__get__(self)
894
910
# No such property
895
raise DBusPropertyNotFound(self.dbus_object_path + ":"
896
+ interface_name + "."
911
raise DBusPropertyNotFound("{}:{}.{}".format(
912
self.dbus_object_path, interface_name, property_name))
899
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
914
@dbus.service.method(dbus.PROPERTIES_IFACE,
900
916
out_signature="v")
901
917
def Get(self, interface_name, property_name):
902
918
"""Standard D-Bus property Get() method, see D-Bus standard.
1083
1100
# Ignore non-D-Bus attributes, and D-Bus attributes
1084
1101
# with the wrong interface name
1085
1102
if (not hasattr(attribute, "_dbus_interface")
1086
or not attribute._dbus_interface
1087
.startswith(orig_interface_name)):
1103
or not attribute._dbus_interface.startswith(
1104
orig_interface_name)):
1089
1106
# Create an alternate D-Bus interface name based on
1090
1107
# the current name
1091
alt_interface = (attribute._dbus_interface
1092
.replace(orig_interface_name,
1093
alt_interface_name))
1108
alt_interface = attribute._dbus_interface.replace(
1109
orig_interface_name, alt_interface_name)
1094
1110
interface_names.add(alt_interface)
1095
1111
# Is this a D-Bus signal?
1096
1112
if getattr(attribute, "_dbus_is_signal", False):
1097
# Extract the original non-method undecorated
1098
# function by black magic
1099
nonmethod_func = (dict(
1113
if sys.version_info.major == 2:
1114
# Extract the original non-method undecorated
1115
# function by black magic
1116
nonmethod_func = (dict(
1100
1117
zip(attribute.func_code.co_freevars,
1101
attribute.__closure__))["func"]
1118
attribute.__closure__))
1119
["func"].cell_contents)
1121
nonmethod_func = attribute
1103
1122
# Create a new, but exactly alike, function
1104
1123
# object, and decorate it to be a new D-Bus signal
1105
1124
# 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)))
1125
if sys.version_info.major == 2:
1126
new_function = types.FunctionType(
1127
nonmethod_func.func_code,
1128
nonmethod_func.func_globals,
1129
nonmethod_func.func_name,
1130
nonmethod_func.func_defaults,
1131
nonmethod_func.func_closure)
1133
new_function = types.FunctionType(
1134
nonmethod_func.__code__,
1135
nonmethod_func.__globals__,
1136
nonmethod_func.__name__,
1137
nonmethod_func.__defaults__,
1138
nonmethod_func.__closure__)
1139
new_function = (dbus.service.signal(
1141
attribute._dbus_signature)(new_function))
1115
1142
# Copy annotations, if any
1117
new_function._dbus_annotations = (
1118
dict(attribute._dbus_annotations))
1144
new_function._dbus_annotations = dict(
1145
attribute._dbus_annotations)
1119
1146
except AttributeError:
1121
1148
# Define a creator of a function to call both the
1141
1170
# object. Decorate it to be a new D-Bus method
1142
1171
# with the alternate D-Bus interface name. Add it
1143
1172
# 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)))
1174
dbus.service.method(
1176
attribute._dbus_in_signature,
1177
attribute._dbus_out_signature)
1178
(types.FunctionType(attribute.func_code,
1179
attribute.func_globals,
1180
attribute.func_name,
1181
attribute.func_defaults,
1182
attribute.func_closure)))
1154
1183
# Copy annotations, if any
1156
attr[attrname]._dbus_annotations = (
1157
dict(attribute._dbus_annotations))
1185
attr[attrname]._dbus_annotations = dict(
1186
attribute._dbus_annotations)
1158
1187
except AttributeError:
1160
1189
# Is this a D-Bus property?
1163
1192
# object, and decorate it to be a new D-Bus
1164
1193
# property with the alternate D-Bus interface
1165
1194
# 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)))
1195
attr[attrname] = (dbus_service_property(
1196
alt_interface, attribute._dbus_signature,
1197
attribute._dbus_access,
1198
attribute._dbus_get_args_options
1200
(types.FunctionType(
1201
attribute.func_code,
1202
attribute.func_globals,
1203
attribute.func_name,
1204
attribute.func_defaults,
1205
attribute.func_closure)))
1179
1206
# Copy annotations, if any
1181
attr[attrname]._dbus_annotations = (
1182
dict(attribute._dbus_annotations))
1208
attr[attrname]._dbus_annotations = dict(
1209
attribute._dbus_annotations)
1183
1210
except AttributeError:
1185
1212
# Is this a D-Bus interface?
1188
1215
# object. Decorate it to be a new D-Bus interface
1189
1216
# with the alternate D-Bus interface name. Add it
1190
1217
# 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)))
1219
dbus_interface_annotations(alt_interface)
1220
(types.FunctionType(attribute.func_code,
1221
attribute.func_globals,
1222
attribute.func_name,
1223
attribute.func_defaults,
1224
attribute.func_closure)))
1200
1226
# Deprecate all alternate interfaces
1201
1227
iname="_AlternateDBusNames_interface_annotation{}"
1202
1228
for interface_name in interface_names:
1203
1230
@dbus_interface_annotations(interface_name)
1204
1231
def func(self):
1205
1232
return { "org.freedesktop.DBus.Deprecated":
1207
1234
# Find an unused name
1208
1235
for aname in (iname.format(i)
1209
1236
for i in itertools.count()):
1244
1272
client_object_name = str(self.name).translate(
1245
1273
{ord("."): ord("_"),
1246
1274
ord("-"): ord("_")})
1247
self.dbus_object_path = (dbus.ObjectPath
1248
("/clients/" + client_object_name))
1275
self.dbus_object_path = dbus.ObjectPath(
1276
"/clients/" + client_object_name)
1249
1277
DBusObjectWithProperties.__init__(self, self.bus,
1250
1278
self.dbus_object_path)
1252
def notifychangeproperty(transform_func,
1253
dbus_name, type_func=lambda x: x,
1254
variant_level=1, invalidate_only=False,
1280
def notifychangeproperty(transform_func, dbus_name,
1281
type_func=lambda x: x,
1283
invalidate_only=False,
1255
1284
_interface=_interface):
1256
1285
""" Modify a variable so that it's a property which announces
1257
1286
its changes to DBus.
1264
1293
variant_level: D-Bus variant level. Default: 1
1266
1295
attrname = "_{}".format(dbus_name)
1267
1297
def setter(self, value):
1268
1298
if hasattr(self, "dbus_object_path"):
1269
1299
if (not hasattr(self, attrname) or
1270
1300
type_func(getattr(self, attrname, None))
1271
1301
!= type_func(value)):
1272
1302
if invalidate_only:
1273
self.PropertiesChanged(_interface,
1303
self.PropertiesChanged(
1304
_interface, dbus.Dictionary(),
1305
dbus.Array((dbus_name, )))
1278
dbus_value = transform_func(type_func(value),
1307
dbus_value = transform_func(
1309
variant_level = variant_level)
1281
1310
self.PropertyChanged(dbus.String(dbus_name),
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1312
self.PropertiesChanged(
1314
dbus.Dictionary({ dbus.String(dbus_name):
1287
1317
setattr(self, attrname, value)
1289
1319
return property(lambda self: getattr(self, attrname), setter)
1295
1325
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1296
1326
last_enabled = notifychangeproperty(datetime_to_dbus,
1298
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1299
type_func = lambda checker:
1300
checker is not None)
1328
checker = notifychangeproperty(
1329
dbus.Boolean, "CheckerRunning",
1330
type_func = lambda checker: checker is not None)
1301
1331
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1302
1332
"LastCheckedOK")
1303
1333
last_checker_status = notifychangeproperty(dbus.Int16,
1306
1336
datetime_to_dbus, "LastApprovalRequest")
1307
1337
approved_by_default = notifychangeproperty(dbus.Boolean,
1308
1338
"ApprovedByDefault")
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1312
lambda td: td.total_seconds()
1339
approval_delay = notifychangeproperty(
1340
dbus.UInt64, "ApprovalDelay",
1341
type_func = lambda td: td.total_seconds() * 1000)
1314
1342
approval_duration = notifychangeproperty(
1315
1343
dbus.UInt64, "ApprovalDuration",
1316
1344
type_func = lambda td: td.total_seconds() * 1000)
1317
1345
host = notifychangeproperty(dbus.String, "Host")
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1346
timeout = notifychangeproperty(
1347
dbus.UInt64, "Timeout",
1348
type_func = lambda td: td.total_seconds() * 1000)
1321
1349
extended_timeout = notifychangeproperty(
1322
1350
dbus.UInt64, "ExtendedTimeout",
1323
1351
type_func = lambda td: td.total_seconds() * 1000)
1324
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1352
interval = notifychangeproperty(
1353
dbus.UInt64, "Interval",
1354
type_func = lambda td: td.total_seconds() * 1000)
1329
1355
checker_command = notifychangeproperty(dbus.String, "Checker")
1330
1356
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
1357
invalidate_only=True)
1341
1367
DBusObjectWithProperties.__del__(self, *args, **kwargs)
1342
1368
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)
1370
def checker_callback(self, source, condition,
1371
connection, command, *args, **kwargs):
1372
ret = Client.checker_callback(self, source, condition,
1373
connection, command, *args,
1375
exitstatus = self.last_checker_status
1350
1377
# Emit D-Bus signal
1351
1378
self.CheckerCompleted(dbus.Int16(exitstatus),
1352
dbus.Int64(condition),
1353
1380
dbus.String(command))
1355
1382
# Emit D-Bus signal
1356
1383
self.CheckerCompleted(dbus.Int16(-1),
1357
dbus.Int64(condition),
1385
self.last_checker_signal),
1358
1386
dbus.String(command))
1360
return Client.checker_callback(self, pid, condition, command,
1363
1389
def start_checker(self, *args, **kwargs):
1364
1390
old_checker_pid = getattr(self.checker, "pid", None)
1604
1637
if self.enabled:
1605
1638
# Reschedule checker run
1606
1639
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
1640
self.checker_initiator_tag = gobject.timeout_add(
1641
value, self.start_checker)
1642
self.start_checker() # Start one now, too
1611
1644
# Checker - property
1612
@dbus_service_property(_interface, signature="s",
1645
@dbus_service_property(_interface,
1613
1647
access="readwrite")
1614
1648
def Checker_dbus_property(self, value=None):
1615
1649
if value is None: # get
1847
1883
def fingerprint(openpgp):
1848
1884
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1849
1885
# 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))))
1886
datum = gnutls.library.types.gnutls_datum_t(
1887
ctypes.cast(ctypes.c_char_p(openpgp),
1888
ctypes.POINTER(ctypes.c_ubyte)),
1889
ctypes.c_uint(len(openpgp)))
1855
1890
# New empty GnuTLS certificate
1856
1891
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1857
(gnutls.library.functions
1858
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1892
gnutls.library.functions.gnutls_openpgp_crt_init(
1859
1894
# 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))
1895
gnutls.library.functions.gnutls_openpgp_crt_import(
1896
crt, ctypes.byref(datum),
1897
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1864
1898
# Verify the self signature in the key
1865
1899
crtverify = ctypes.c_uint()
1866
(gnutls.library.functions
1867
.gnutls_openpgp_crt_verify_self(crt, 0,
1868
ctypes.byref(crtverify)))
1900
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1901
crt, 0, ctypes.byref(crtverify))
1869
1902
if crtverify.value != 0:
1870
1903
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1871
raise (gnutls.errors.CertificateSecurityError
1904
raise gnutls.errors.CertificateSecurityError(
1873
1906
# New buffer for the fingerprint
1874
1907
buf = ctypes.create_string_buffer(20)
1875
1908
buf_len = ctypes.c_size_t()
1876
1909
# 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)))
1910
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1911
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1880
1912
# Deinit the certificate
1881
1913
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1882
1914
# Convert the buffer to a Python bytestring
2051
2092
def add_pipe(self, parent_pipe, proc):
2052
2093
# 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,
2094
gobject.io_add_watch(
2095
parent_pipe.fileno(),
2096
gobject.IO_IN | gobject.IO_HUP,
2097
functools.partial(self.handle_ipc,
2098
parent_pipe = parent_pipe,
2060
def handle_ipc(self, source, condition, parent_pipe=None,
2061
proc = None, client_object=None):
2101
def handle_ipc(self, source, condition,
2104
client_object=None):
2062
2105
# error, or the other end of multiprocessing.Pipe has closed
2063
2106
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2064
2107
# Wait for other process to exit
2151
2194
# avoid excessive use of external libraries.
2153
2196
# 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
2197
Token = collections.namedtuple("Token", (
2198
"regexp", # To match token; if "value" is not None, must have
2199
# a "group" containing digits
2200
"value", # datetime.timedelta or None
2201
"followers")) # Tokens valid after this token
2163
2202
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2164
2203
# the "duration" ABNF definition in RFC 3339, Appendix A.
2165
2204
token_end = Token(re.compile(r"$"), None, frozenset())
2166
2205
token_second = Token(re.compile(r"(\d+)S"),
2167
2206
datetime.timedelta(seconds=1),
2168
frozenset((token_end,)))
2207
frozenset((token_end, )))
2169
2208
token_minute = Token(re.compile(r"(\d+)M"),
2170
2209
datetime.timedelta(minutes=1),
2171
2210
frozenset((token_second, token_end)))
2396
2436
# Override the settings from the config file with command line
2397
2437
# options, if set.
2398
2438
for option in ("interface", "address", "port", "debug",
2399
"priority", "servicename", "configdir",
2400
"use_dbus", "use_ipv6", "debuglevel", "restore",
2401
"statedir", "socket", "foreground", "zeroconf"):
2439
"priority", "servicename", "configdir", "use_dbus",
2440
"use_ipv6", "debuglevel", "restore", "statedir",
2441
"socket", "foreground", "zeroconf"):
2402
2442
value = getattr(options, option)
2403
2443
if value is not None:
2404
2444
server_settings[option] = value
2463
2501
socketfd = None
2464
2502
if server_settings["socket"] != "":
2465
2503
socketfd = server_settings["socket"]
2466
tcp_server = MandosServer((server_settings["address"],
2467
server_settings["port"]),
2469
interface=(server_settings["interface"]
2473
server_settings["priority"],
2504
tcp_server = MandosServer(
2505
(server_settings["address"], server_settings["port"]),
2507
interface=(server_settings["interface"] or None),
2509
gnutls_priority=server_settings["priority"],
2476
2512
if not foreground:
2477
2513
pidfilename = "/run/mandos.pid"
2478
2514
if not os.path.isdir("/run/."):
2479
2515
pidfilename = "/var/run/mandos.pid"
2482
pidfile = open(pidfilename, "w")
2518
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2483
2519
except IOError as e:
2484
2520
logger.error("Could not open file %r", pidfilename,
2541
2577
bus_name = dbus.service.BusName("se.recompile.Mandos",
2542
bus, do_not_queue=True)
2543
old_bus_name = (dbus.service.BusName
2544
("se.bsnet.fukt.Mandos", bus,
2546
except dbus.exceptions.NameExistsException as e:
2580
old_bus_name = dbus.service.BusName(
2581
"se.bsnet.fukt.Mandos", bus,
2583
except dbus.exceptions.DBusException as e:
2547
2584
logger.error("Disabling D-Bus:", exc_info=e)
2548
2585
use_dbus = False
2549
2586
server_settings["use_dbus"] = False
2550
2587
tcp_server.use_dbus = False
2552
2589
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2553
service = AvahiServiceToSyslog(name =
2554
server_settings["servicename"],
2555
servicetype = "_mandos._tcp",
2556
protocol = protocol, bus = bus)
2590
service = AvahiServiceToSyslog(
2591
name = server_settings["servicename"],
2592
servicetype = "_mandos._tcp",
2593
protocol = protocol,
2557
2595
if server_settings["interface"]:
2558
service.interface = (if_nametoindex
2559
(server_settings["interface"]
2596
service.interface = if_nametoindex(
2597
server_settings["interface"].encode("utf-8"))
2562
2599
global multiprocessing_manager
2563
2600
multiprocessing_manager = multiprocessing.Manager()
2582
2619
if server_settings["restore"]:
2584
2621
with open(stored_state_path, "rb") as stored_state:
2585
clients_data, old_client_settings = (pickle.load
2622
clients_data, old_client_settings = pickle.load(
2587
2624
os.remove(stored_state_path)
2588
2625
except IOError as e:
2589
2626
if e.errno == errno.ENOENT:
2590
logger.warning("Could not load persistent state: {}"
2591
.format(os.strerror(e.errno)))
2627
logger.warning("Could not load persistent state:"
2628
" {}".format(os.strerror(e.errno)))
2593
2630
logger.critical("Could not load persistent state:",
2596
2633
except EOFError as e:
2597
2634
logger.warning("Could not load persistent state: "
2598
"EOFError:", exc_info=e)
2600
2638
with PGPEngine() as pgp:
2601
2639
for client_name, client in clients_data.items():
2630
2668
if not client["last_checked_ok"]:
2631
2669
logger.warning(
2632
2670
"disabling client {} - Client never "
2633
"performed a successful checker"
2634
.format(client_name))
2671
"performed a successful checker".format(
2635
2673
client["enabled"] = False
2636
2674
elif client["last_checker_status"] != 0:
2637
2675
logger.warning(
2638
2676
"disabling client {} - Client last"
2639
" checker failed with error code {}"
2640
.format(client_name,
2641
client["last_checker_status"]))
2677
" checker failed with error code"
2680
client["last_checker_status"]))
2642
2681
client["enabled"] = False
2644
client["expires"] = (datetime.datetime
2646
+ client["timeout"])
2683
client["expires"] = (
2684
datetime.datetime.utcnow()
2685
+ client["timeout"])
2647
2686
logger.debug("Last checker succeeded,"
2648
" keeping {} enabled"
2649
.format(client_name))
2687
" keeping {} enabled".format(
2651
client["secret"] = (
2652
pgp.decrypt(client["encrypted_secret"],
2653
client_settings[client_name]
2690
client["secret"] = pgp.decrypt(
2691
client["encrypted_secret"],
2692
client_settings[client_name]["secret"])
2655
2693
except PGPError:
2656
2694
# If decryption fails, we use secret from new settings
2657
logger.debug("Failed to decrypt {} old secret"
2658
.format(client_name))
2659
client["secret"] = (
2660
client_settings[client_name]["secret"])
2695
logger.debug("Failed to decrypt {} old secret".format(
2697
client["secret"] = (client_settings[client_name]
2662
2700
# Add/remove clients based on new changes made to config
2663
2701
for client_name in (set(old_client_settings)
2692
2731
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2695
@alternate_dbus_interfaces({"se.recompile.Mandos":
2696
"se.bsnet.fukt.Mandos"})
2735
@alternate_dbus_interfaces(
2736
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2697
2737
class MandosDBusService(DBusObjectWithProperties):
2698
2738
"""A D-Bus proxy object"""
2699
2740
def __init__(self):
2700
2741
dbus.service.Object.__init__(self, bus, "/")
2701
2743
_interface = "se.recompile.Mandos"
2703
2745
@dbus_interface_annotations(_interface)
2704
2746
def _foo(self):
2705
return { "org.freedesktop.DBus.Property"
2706
".EmitsChangedSignal":
2748
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2709
2751
@dbus.service.signal(_interface, signature="o")
2710
2752
def ClientAdded(self, objpath):
2794
2835
del client_settings[client.name]["secret"]
2797
with (tempfile.NamedTemporaryFile
2798
(mode='wb', suffix=".pickle", prefix='clients-',
2799
dir=os.path.dirname(stored_state_path),
2800
delete=False)) as stored_state:
2838
with tempfile.NamedTemporaryFile(
2842
dir=os.path.dirname(stored_state_path),
2843
delete=False) as stored_state:
2801
2844
pickle.dump((clients, client_settings), stored_state)
2802
tempname=stored_state.name
2845
tempname = stored_state.name
2803
2846
os.rename(tempname, stored_state_path)
2804
2847
except (IOError, OSError) as e: