86
101
except ImportError:
87
102
SO_BINDTODEVICE = None
104
if sys.version_info.major == 2:
90
108
stored_state_file = "clients.pickle"
92
110
logger = logging.getLogger()
93
syslogger = (logging.handlers.SysLogHandler
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
address = str("/dev/log")))
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
114
if_nametoindex = ctypes.cdll.LoadLibrary(
115
ctypes.util.find_library("c")).if_nametoindex
101
116
except (OSError, AttributeError):
102
118
def if_nametoindex(interface):
103
119
"Get an interface index the hard way, i.e. using fcntl()"
104
120
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
105
121
with contextlib.closing(socket.socket()) as s:
106
122
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
struct.pack(str("16s16x"),
109
interface_index = struct.unpack(str("I"),
123
struct.pack(b"16s16x", interface))
124
interface_index = struct.unpack("I", ifreq[16:20])[0]
111
125
return interface_index
114
128
def initlogger(debug, level=logging.WARNING):
115
129
"""init logger and add loglevel"""
132
syslogger = (logging.handlers.SysLogHandler(
133
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
134
address = "/dev/log"))
117
135
syslogger.setFormatter(logging.Formatter
118
136
('Mandos [%(process)d]: %(levelname)s:'
172
189
def password_encode(self, password):
173
190
# Passphrase can not be empty and can not contain newlines or
174
191
# NUL bytes. So we prefix it and hex encode it.
175
return b"mandos" + binascii.hexlify(password)
192
encoded = b"mandos" + binascii.hexlify(password)
193
if len(encoded) > 2048:
194
# GnuPG can't handle long passwords, so encode differently
195
encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
196
.replace(b"\n", b"\\n")
197
.replace(b"\0", b"\\x00"))
177
200
def encrypt(self, data, password):
178
self.gnupg.passphrase = self.password_encode(password)
179
with open(os.devnull, "w") as devnull:
181
proc = self.gnupg.run(['--symmetric'],
182
create_fhs=['stdin', 'stdout'],
183
attach_fhs={'stderr': devnull})
184
with contextlib.closing(proc.handles['stdin']) as f:
186
with contextlib.closing(proc.handles['stdout']) as f:
187
ciphertext = f.read()
191
self.gnupg.passphrase = None
201
passphrase = self.password_encode(password)
202
with tempfile.NamedTemporaryFile(
203
dir=self.tempdir) as passfile:
204
passfile.write(passphrase)
206
proc = subprocess.Popen(['gpg', '--symmetric',
210
stdin = subprocess.PIPE,
211
stdout = subprocess.PIPE,
212
stderr = subprocess.PIPE)
213
ciphertext, err = proc.communicate(input = data)
214
if proc.returncode != 0:
192
216
return ciphertext
194
218
def decrypt(self, data, password):
195
self.gnupg.passphrase = self.password_encode(password)
196
with open(os.devnull, "w") as devnull:
198
proc = self.gnupg.run(['--decrypt'],
199
create_fhs=['stdin', 'stdout'],
200
attach_fhs={'stderr': devnull})
201
with contextlib.closing(proc.handles['stdin']) as f:
203
with contextlib.closing(proc.handles['stdout']) as f:
204
decrypted_plaintext = f.read()
208
self.gnupg.passphrase = None
219
passphrase = self.password_encode(password)
220
with tempfile.NamedTemporaryFile(
221
dir = self.tempdir) as passfile:
222
passfile.write(passphrase)
224
proc = subprocess.Popen(['gpg', '--decrypt',
228
stdin = subprocess.PIPE,
229
stdout = subprocess.PIPE,
230
stderr = subprocess.PIPE)
231
decrypted_plaintext, err = proc.communicate(input = data)
232
if proc.returncode != 0:
209
234
return decrypted_plaintext
213
237
class AvahiError(Exception):
214
238
def __init__(self, value, *args, **kwargs):
215
239
self.value = value
216
super(AvahiError, self).__init__(value, *args, **kwargs)
217
def __unicode__(self):
218
return unicode(repr(self.value))
240
return super(AvahiError, self).__init__(value, *args,
220
244
class AvahiServiceError(AvahiError):
223
248
class AvahiGroupError(AvahiError):
427
466
runtime_expansions: Allowed attributes for runtime expansion.
428
467
expires: datetime.datetime(); time (UTC) when a client will be
429
468
disabled, or None
469
server_settings: The server_settings dict from main()
432
472
runtime_expansions = ("approval_delay", "approval_duration",
433
"created", "enabled", "fingerprint",
434
"host", "interval", "last_checked_ok",
473
"created", "enabled", "expires",
474
"fingerprint", "host", "interval",
475
"last_approval_request", "last_checked_ok",
435
476
"last_enabled", "name", "timeout")
436
client_defaults = { "timeout": "5m",
437
"extended_timeout": "15m",
439
"checker": "fping -q -- %%(host)s",
441
"approval_delay": "0s",
442
"approval_duration": "1s",
443
"approved_by_default": "True",
447
def timeout_milliseconds(self):
448
"Return the 'timeout' attribute in milliseconds"
449
return timedelta_to_milliseconds(self.timeout)
451
def extended_timeout_milliseconds(self):
452
"Return the 'extended_timeout' attribute in milliseconds"
453
return timedelta_to_milliseconds(self.extended_timeout)
455
def interval_milliseconds(self):
456
"Return the 'interval' attribute in milliseconds"
457
return timedelta_to_milliseconds(self.interval)
459
def approval_delay_milliseconds(self):
460
return timedelta_to_milliseconds(self.approval_delay)
479
"extended_timeout": "PT15M",
481
"checker": "fping -q -- %%(host)s",
483
"approval_delay": "PT0S",
484
"approval_duration": "PT1S",
485
"approved_by_default": "True",
463
490
def config_parser(config):
464
491
"""Construct a new dict of client settings of this form:
677
703
self.current_checker_command)
678
704
# Start a new checker if needed
679
705
if self.checker is None:
706
# Escape attributes for the shell
708
attr: re.escape(str(getattr(self, attr)))
709
for attr in self.runtime_expansions }
681
# In case checker_command has exactly one % operator
682
command = self.checker_command % self.host
684
# Escape attributes for the shell
685
escaped_attrs = dict(
687
re.escape(unicode(str(getattr(self, attr, "")),
691
self.runtime_expansions)
694
command = self.checker_command % escaped_attrs
695
except TypeError as error:
696
logger.error('Could not format string "%s"',
697
self.checker_command, exc_info=error)
698
return True # Try again later
711
command = self.checker_command % escaped_attrs
712
except TypeError as error:
713
logger.error('Could not format string "%s"',
714
self.checker_command,
716
return True # Try again later
699
717
self.current_checker_command = command
701
logger.info("Starting checker %r for %s",
719
logger.info("Starting checker %r for %s", command,
703
721
# We don't need to redirect stdout and stderr, since
704
722
# in normal mode, that is already done by daemon(),
705
723
# and in debug mode we don't want to. (Stdin is
706
724
# always replaced by /dev/null.)
725
# The exception is when not debugging but nevertheless
726
# running in the foreground; use the previously
729
if (not self.server_settings["debug"]
730
and self.server_settings["foreground"]):
731
popen_args.update({"stdout": wnull,
707
733
self.checker = subprocess.Popen(command,
710
self.checker_callback_tag = (gobject.child_watch_add
712
self.checker_callback,
714
# The checker may have completed before the gobject
715
# watch was added. Check for this.
738
except OSError as error:
739
logger.error("Failed to start subprocess",
742
self.checker_callback_tag = gobject.child_watch_add(
743
self.checker.pid, self.checker_callback, data=command)
744
# The checker may have completed before the gobject
745
# watch was added. Check for this.
716
747
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
718
gobject.source_remove(self.checker_callback_tag)
719
self.checker_callback(pid, status, command)
720
748
except OSError as error:
721
logger.error("Failed to start subprocess",
749
if error.errno == errno.ECHILD:
750
# This should never happen
751
logger.error("Child process vanished",
756
gobject.source_remove(self.checker_callback_tag)
757
self.checker_callback(pid, status, command)
723
758
# Re-run this periodically if run by gobject.timeout_add
843
885
If called like _is_dbus_thing("method") it returns a function
844
886
suitable for use as predicate to inspect.getmembers().
846
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
888
return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
849
891
def _get_all_dbus_things(self, thing):
850
892
"""Returns a generator of (name, attribute) pairs
852
return ((getattr(athing.__get__(self), "_dbus_name",
894
return ((getattr(athing.__get__(self), "_dbus_name", name),
854
895
athing.__get__(self))
855
896
for cls in self.__class__.__mro__
856
897
for name, athing in
857
inspect.getmembers(cls,
858
self._is_dbus_thing(thing)))
898
inspect.getmembers(cls, self._is_dbus_thing(thing)))
860
900
def _get_dbus_property(self, interface_name, property_name):
861
901
"""Returns a bound method if one exists which is a D-Bus
862
902
property with the specified name and interface.
864
for cls in self.__class__.__mro__:
865
for name, value in (inspect.getmembers
867
self._is_dbus_thing("property"))):
904
for cls in self.__class__.__mro__:
905
for name, value in inspect.getmembers(
906
cls, self._is_dbus_thing("property")):
868
907
if (value._dbus_name == property_name
869
908
and value._dbus_interface == interface_name):
870
909
return value.__get__(self)
872
911
# No such property
873
raise DBusPropertyNotFound(self.dbus_object_path + ":"
874
+ interface_name + "."
912
raise DBusPropertyNotFound("{}:{}.{}".format(
913
self.dbus_object_path, interface_name, property_name))
877
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
915
@dbus.service.method(dbus.PROPERTIES_IFACE,
878
917
out_signature="v")
879
918
def Get(self, interface_name, property_name):
880
919
"""Standard D-Bus property Get() method, see D-Bus standard.
1010
1060
return xmlstring
1013
def datetime_to_dbus (dt, variant_level=0):
1063
def datetime_to_dbus(dt, variant_level=0):
1014
1064
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1016
1066
return dbus.String("", variant_level = variant_level)
1017
return dbus.String(dt.isoformat(),
1018
variant_level=variant_level)
1021
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
1023
"""Applied to an empty subclass of a D-Bus object, this metaclass
1024
will add additional D-Bus attributes matching a certain pattern.
1067
return dbus.String(dt.isoformat(), variant_level=variant_level)
1070
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1071
"""A class decorator; applied to a subclass of
1072
dbus.service.Object, it will add alternate D-Bus attributes with
1073
interface names according to the "alt_interface_names" mapping.
1076
@alternate_dbus_interfaces({"org.example.Interface":
1077
"net.example.AlternateInterface"})
1078
class SampleDBusObject(dbus.service.Object):
1079
@dbus.service.method("org.example.Interface")
1080
def SampleDBusMethod():
1083
The above "SampleDBusMethod" on "SampleDBusObject" will be
1084
reachable via two interfaces: "org.example.Interface" and
1085
"net.example.AlternateInterface", the latter of which will have
1086
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1087
"true", unless "deprecate" is passed with a False value.
1089
This works for methods and signals, and also for D-Bus properties
1090
(from DBusObjectWithProperties) and interfaces (from the
1091
dbus_interface_annotations decorator).
1026
def __new__(mcs, name, bases, attr):
1027
# Go through all the base classes which could have D-Bus
1028
# methods, signals, or properties in them
1029
old_interface_names = []
1030
for base in (b for b in bases
1031
if issubclass(b, dbus.service.Object)):
1032
# Go though all attributes of the base class
1033
for attrname, attribute in inspect.getmembers(base):
1095
for orig_interface_name, alt_interface_name in (
1096
alt_interface_names.items()):
1098
interface_names = set()
1099
# Go though all attributes of the class
1100
for attrname, attribute in inspect.getmembers(cls):
1034
1101
# Ignore non-D-Bus attributes, and D-Bus attributes
1035
1102
# with the wrong interface name
1036
1103
if (not hasattr(attribute, "_dbus_interface")
1037
or not attribute._dbus_interface
1038
.startswith("se.recompile.Mandos")):
1104
or not attribute._dbus_interface.startswith(
1105
orig_interface_name)):
1040
1107
# Create an alternate D-Bus interface name based on
1041
1108
# the current name
1042
alt_interface = (attribute._dbus_interface
1043
.replace("se.recompile.Mandos",
1044
"se.bsnet.fukt.Mandos"))
1045
if alt_interface != attribute._dbus_interface:
1046
old_interface_names.append(alt_interface)
1109
alt_interface = attribute._dbus_interface.replace(
1110
orig_interface_name, alt_interface_name)
1111
interface_names.add(alt_interface)
1047
1112
# Is this a D-Bus signal?
1048
1113
if getattr(attribute, "_dbus_is_signal", False):
1049
# Extract the original non-method function by
1114
# Extract the original non-method undecorated
1115
# function by black magic
1051
1116
nonmethod_func = (dict(
1052
zip(attribute.func_code.co_freevars,
1053
attribute.__closure__))["func"]
1117
zip(attribute.func_code.co_freevars,
1118
attribute.__closure__))
1119
["func"].cell_contents)
1055
1120
# Create a new, but exactly alike, function
1056
1121
# object, and decorate it to be a new D-Bus signal
1057
1122
# with the alternate D-Bus interface name
1058
new_function = (dbus.service.signal
1060
attribute._dbus_signature)
1123
new_function = (dbus.service.signal(
1124
alt_interface, attribute._dbus_signature)
1061
1125
(types.FunctionType(
1062
nonmethod_func.func_code,
1063
nonmethod_func.func_globals,
1064
nonmethod_func.func_name,
1065
nonmethod_func.func_defaults,
1066
nonmethod_func.func_closure)))
1126
nonmethod_func.func_code,
1127
nonmethod_func.func_globals,
1128
nonmethod_func.func_name,
1129
nonmethod_func.func_defaults,
1130
nonmethod_func.func_closure)))
1067
1131
# Copy annotations, if any
1069
new_function._dbus_annotations = (
1070
dict(attribute._dbus_annotations))
1133
new_function._dbus_annotations = dict(
1134
attribute._dbus_annotations)
1071
1135
except AttributeError:
1073
1137
# Define a creator of a function to call both the
1074
# old and new functions, so both the old and new
1075
# signals gets sent when the function is called
1138
# original and alternate functions, so both the
1139
# original and alternate signals gets sent when
1140
# the function is called
1076
1141
def fixscope(func1, func2):
1077
1142
"""This function is a scope container to pass
1078
1143
func1 and func2 to the "call_both" function
1079
1144
outside of its arguments"""
1080
1146
def call_both(*args, **kwargs):
1081
1147
"""This function will emit two D-Bus
1082
1148
signals by calling func1 and func2"""
1083
1149
func1(*args, **kwargs)
1084
1150
func2(*args, **kwargs)
1085
1152
return call_both
1086
1153
# Create the "call_both" function and add it to
1088
attr[attrname] = fixscope(attribute,
1155
attr[attrname] = fixscope(attribute, new_function)
1090
1156
# Is this a D-Bus method?
1091
1157
elif getattr(attribute, "_dbus_is_method", False):
1092
1158
# Create a new, but exactly alike, function
1093
1159
# object. Decorate it to be a new D-Bus method
1094
1160
# with the alternate D-Bus interface name. Add it
1095
1161
# to the class.
1096
attr[attrname] = (dbus.service.method
1098
attribute._dbus_in_signature,
1099
attribute._dbus_out_signature)
1101
(attribute.func_code,
1102
attribute.func_globals,
1103
attribute.func_name,
1104
attribute.func_defaults,
1105
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)))
1106
1172
# Copy annotations, if any
1108
attr[attrname]._dbus_annotations = (
1109
dict(attribute._dbus_annotations))
1174
attr[attrname]._dbus_annotations = dict(
1175
attribute._dbus_annotations)
1110
1176
except AttributeError:
1112
1178
# Is this a D-Bus property?
1140
1204
# object. Decorate it to be a new D-Bus interface
1141
1205
# with the alternate D-Bus interface name. Add it
1142
1206
# to the class.
1143
attr[attrname] = (dbus_interface_annotations
1146
(attribute.func_code,
1147
attribute.func_globals,
1148
attribute.func_name,
1149
attribute.func_defaults,
1150
attribute.func_closure)))
1151
# Deprecate all old interfaces
1152
basename="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1153
for old_interface_name in old_interface_names:
1154
@dbus_interface_annotations(old_interface_name)
1156
return { "org.freedesktop.DBus.Deprecated": "true" }
1157
# Find an unused name
1158
for aname in (basename.format(i) for i in
1160
if aname not in attr:
1163
return type.__new__(mcs, name, bases, attr)
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)))
1215
# Deprecate all alternate interfaces
1216
iname="_AlternateDBusNames_interface_annotation{}"
1217
for interface_name in interface_names:
1219
@dbus_interface_annotations(interface_name)
1221
return { "org.freedesktop.DBus.Deprecated":
1223
# Find an unused name
1224
for aname in (iname.format(i)
1225
for i in itertools.count()):
1226
if aname not in attr:
1230
# Replace the class with a new subclass of it with
1231
# methods, signals, etc. as created above.
1232
cls = type(b"{}Alternate".format(cls.__name__),
1239
@alternate_dbus_interfaces({"se.recompile.Mandos":
1240
"se.bsnet.fukt.Mandos"})
1166
1241
class ClientDBus(Client, DBusObjectWithProperties):
1167
1242
"""A Client class using D-Bus
1202
1281
to the D-Bus. Default: no transform
1203
1282
variant_level: D-Bus variant level. Default: 1
1205
attrname = "_{0}".format(dbus_name)
1284
attrname = "_{}".format(dbus_name)
1206
1286
def setter(self, value):
1207
1287
if hasattr(self, "dbus_object_path"):
1208
1288
if (not hasattr(self, attrname) or
1209
1289
type_func(getattr(self, attrname, None))
1210
1290
!= type_func(value)):
1211
dbus_value = transform_func(type_func(value),
1214
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):
1216
1306
setattr(self, attrname, value)
1218
1308
return property(lambda self: getattr(self, attrname), setter)
1221
1310
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1222
1311
approvals_pending = notifychangeproperty(dbus.Boolean,
1223
1312
"ApprovalPending",
1236
1325
datetime_to_dbus, "LastApprovalRequest")
1237
1326
approved_by_default = notifychangeproperty(dbus.Boolean,
1238
1327
"ApprovedByDefault")
1239
approval_delay = notifychangeproperty(dbus.UInt64,
1242
timedelta_to_milliseconds)
1328
approval_delay = notifychangeproperty(
1329
dbus.UInt64, "ApprovalDelay",
1330
type_func = lambda td: td.total_seconds() * 1000)
1243
1331
approval_duration = notifychangeproperty(
1244
1332
dbus.UInt64, "ApprovalDuration",
1245
type_func = timedelta_to_milliseconds)
1333
type_func = lambda td: td.total_seconds() * 1000)
1246
1334
host = notifychangeproperty(dbus.String, "Host")
1247
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1249
timedelta_to_milliseconds)
1335
timeout = notifychangeproperty(
1336
dbus.UInt64, "Timeout",
1337
type_func = lambda td: td.total_seconds() * 1000)
1250
1338
extended_timeout = notifychangeproperty(
1251
1339
dbus.UInt64, "ExtendedTimeout",
1252
type_func = timedelta_to_milliseconds)
1253
interval = notifychangeproperty(dbus.UInt64,
1256
timedelta_to_milliseconds)
1340
type_func = lambda td: td.total_seconds() * 1000)
1341
interval = notifychangeproperty(
1342
dbus.UInt64, "Interval",
1343
type_func = lambda td: td.total_seconds() * 1000)
1257
1344
checker_command = notifychangeproperty(dbus.String, "Checker")
1345
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1346
invalidate_only=True)
1259
1348
del notifychangeproperty
1495
1579
return datetime_to_dbus(self.last_approval_request)
1497
1581
# Timeout - property
1498
@dbus_service_property(_interface, signature="t",
1582
@dbus_service_property(_interface,
1499
1584
access="readwrite")
1500
1585
def Timeout_dbus_property(self, value=None):
1501
1586
if value is None: # get
1502
return dbus.UInt64(self.timeout_milliseconds())
1587
return dbus.UInt64(self.timeout.total_seconds() * 1000)
1588
old_timeout = self.timeout
1503
1589
self.timeout = datetime.timedelta(0, 0, 0, value)
1504
# Reschedule timeout
1590
# Reschedule disabling
1505
1591
if self.enabled:
1506
1592
now = datetime.datetime.utcnow()
1507
time_to_die = timedelta_to_milliseconds(
1508
(self.last_checked_ok + self.timeout) - now)
1509
if time_to_die <= 0:
1593
self.expires += self.timeout - old_timeout
1594
if self.expires <= now:
1510
1595
# The timeout has passed
1513
self.expires = (now +
1514
datetime.timedelta(milliseconds =
1516
1598
if (getattr(self, "disable_initiator_tag", None)
1519
1601
gobject.source_remove(self.disable_initiator_tag)
1520
self.disable_initiator_tag = (gobject.timeout_add
1602
self.disable_initiator_tag = gobject.timeout_add(
1603
int((self.expires - now).total_seconds() * 1000),
1524
1606
# ExtendedTimeout - property
1525
@dbus_service_property(_interface, signature="t",
1607
@dbus_service_property(_interface,
1526
1609
access="readwrite")
1527
1610
def ExtendedTimeout_dbus_property(self, value=None):
1528
1611
if value is None: # get
1529
return dbus.UInt64(self.extended_timeout_milliseconds())
1612
return dbus.UInt64(self.extended_timeout.total_seconds()
1530
1614
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1532
1616
# Interval - property
1533
@dbus_service_property(_interface, signature="t",
1617
@dbus_service_property(_interface,
1534
1619
access="readwrite")
1535
1620
def Interval_dbus_property(self, value=None):
1536
1621
if value is None: # get
1537
return dbus.UInt64(self.interval_milliseconds())
1622
return dbus.UInt64(self.interval.total_seconds() * 1000)
1538
1623
self.interval = datetime.timedelta(0, 0, 0, value)
1539
1624
if getattr(self, "checker_initiator_tag", None) is None:
1541
1626
if self.enabled:
1542
1627
# Reschedule checker run
1543
1628
gobject.source_remove(self.checker_initiator_tag)
1544
self.checker_initiator_tag = (gobject.timeout_add
1545
(value, self.start_checker))
1546
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
1548
1633
# Checker - property
1549
@dbus_service_property(_interface, signature="s",
1634
@dbus_service_property(_interface,
1550
1636
access="readwrite")
1551
1637
def Checker_dbus_property(self, value=None):
1552
1638
if value is None: # get
1553
1639
return dbus.String(self.checker_command)
1554
self.checker_command = unicode(value)
1640
self.checker_command = str(value)
1556
1642
# CheckerRunning - property
1557
@dbus_service_property(_interface, signature="b",
1643
@dbus_service_property(_interface,
1558
1645
access="readwrite")
1559
1646
def CheckerRunning_dbus_property(self, value=None):
1560
1647
if value is None: # get
1788
1872
def fingerprint(openpgp):
1789
1873
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1790
1874
# New GnuTLS "datum" with the OpenPGP public key
1791
datum = (gnutls.library.types
1792
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1795
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)))
1796
1879
# New empty GnuTLS certificate
1797
1880
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1798
(gnutls.library.functions
1799
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1881
gnutls.library.functions.gnutls_openpgp_crt_init(
1800
1883
# Import the OpenPGP public key into the certificate
1801
(gnutls.library.functions
1802
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1803
gnutls.library.constants
1804
.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)
1805
1887
# Verify the self signature in the key
1806
1888
crtverify = ctypes.c_uint()
1807
(gnutls.library.functions
1808
.gnutls_openpgp_crt_verify_self(crt, 0,
1809
ctypes.byref(crtverify)))
1889
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
crt, 0, ctypes.byref(crtverify))
1810
1891
if crtverify.value != 0:
1811
1892
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1812
raise (gnutls.errors.CertificateSecurityError
1893
raise gnutls.errors.CertificateSecurityError(
1814
1895
# New buffer for the fingerprint
1815
1896
buf = ctypes.create_string_buffer(20)
1816
1897
buf_len = ctypes.c_size_t()
1817
1898
# Get the fingerprint from the certificate into the buffer
1818
(gnutls.library.functions
1819
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1820
ctypes.byref(buf_len)))
1899
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1821
1901
# Deinit the certificate
1822
1902
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1823
1903
# Convert the buffer to a Python bytestring
1873
1954
interface: None or a network interface name (string)
1874
1955
use_ipv6: Boolean; to use IPv6 or not
1876
1958
def __init__(self, server_address, RequestHandlerClass,
1877
interface=None, use_ipv6=True):
1962
"""If socketfd is set, use that file descriptor instead of
1963
creating a new one with socket.socket().
1878
1965
self.interface = interface
1880
1967
self.address_family = socket.AF_INET6
1968
if socketfd is not None:
1969
# Save the file descriptor
1970
self.socketfd = socketfd
1971
# Save the original socket.socket() function
1972
self.socket_socket = socket.socket
1973
# To implement --socket, we monkey patch socket.socket.
1975
# (When socketserver.TCPServer is a new-style class, we
1976
# could make self.socket into a property instead of monkey
1977
# patching socket.socket.)
1979
# Create a one-time-only replacement for socket.socket()
1980
@functools.wraps(socket.socket)
1981
def socket_wrapper(*args, **kwargs):
1982
# Restore original function so subsequent calls are
1984
socket.socket = self.socket_socket
1985
del self.socket_socket
1986
# This time only, return a new socket object from the
1987
# saved file descriptor.
1988
return socket.fromfd(self.socketfd, *args, **kwargs)
1989
# Replace socket.socket() function with wrapper
1990
socket.socket = socket_wrapper
1991
# The socketserver.TCPServer.__init__ will call
1992
# socket.socket(), which might be our replacement,
1993
# socket_wrapper(), if socketfd was set.
1881
1994
socketserver.TCPServer.__init__(self, server_address,
1882
1995
RequestHandlerClass)
1883
1997
def server_bind(self):
1884
1998
"""This overrides the normal server_bind() function
1885
1999
to bind to an interface if one was specified, and also NOT to
1960
2081
def add_pipe(self, parent_pipe, proc):
1961
2082
# Call "handle_ipc" for both data and EOF events
1962
gobject.io_add_watch(parent_pipe.fileno(),
1963
gobject.IO_IN | gobject.IO_HUP,
1964
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,
1969
def handle_ipc(self, source, condition, parent_pipe=None,
1970
proc = None, client_object=None):
1972
gobject.IO_IN: "IN", # There is data to read.
1973
gobject.IO_OUT: "OUT", # Data can be written (without
1975
gobject.IO_PRI: "PRI", # There is urgent data to read.
1976
gobject.IO_ERR: "ERR", # Error condition.
1977
gobject.IO_HUP: "HUP" # Hung up (the connection has been
1978
# broken, usually for pipes and
1981
conditions_string = ' | '.join(name
1983
condition_names.iteritems()
1984
if cond & condition)
2090
def handle_ipc(self, source, condition,
2093
client_object=None):
1985
2094
# error, or the other end of multiprocessing.Pipe has closed
1986
if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
2095
if condition & (gobject.IO_ERR | gobject.IO_HUP):
1987
2096
# Wait for other process to exit
2158
def rfc3339_duration_to_delta(duration):
2159
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2161
>>> rfc3339_duration_to_delta("P7D")
2162
datetime.timedelta(7)
2163
>>> rfc3339_duration_to_delta("PT60S")
2164
datetime.timedelta(0, 60)
2165
>>> rfc3339_duration_to_delta("PT60M")
2166
datetime.timedelta(0, 3600)
2167
>>> rfc3339_duration_to_delta("PT24H")
2168
datetime.timedelta(1)
2169
>>> rfc3339_duration_to_delta("P1W")
2170
datetime.timedelta(7)
2171
>>> rfc3339_duration_to_delta("PT5M30S")
2172
datetime.timedelta(0, 330)
2173
>>> rfc3339_duration_to_delta("P1DT3M20S")
2174
datetime.timedelta(1, 200)
2177
# Parsing an RFC 3339 duration with regular expressions is not
2178
# possible - there would have to be multiple places for the same
2179
# values, like seconds. The current code, while more esoteric, is
2180
# cleaner without depending on a parsing library. If Python had a
2181
# built-in library for parsing we would use it, but we'd like to
2182
# avoid excessive use of external libraries.
2184
# New type for defining tokens, syntax, and semantics all-in-one
2185
Token = collections.namedtuple("Token", (
2186
"regexp", # To match token; if "value" is not None, must have
2187
# a "group" containing digits
2188
"value", # datetime.timedelta or None
2189
"followers")) # Tokens valid after this token
2190
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2191
# the "duration" ABNF definition in RFC 3339, Appendix A.
2192
token_end = Token(re.compile(r"$"), None, frozenset())
2193
token_second = Token(re.compile(r"(\d+)S"),
2194
datetime.timedelta(seconds=1),
2195
frozenset((token_end, )))
2196
token_minute = Token(re.compile(r"(\d+)M"),
2197
datetime.timedelta(minutes=1),
2198
frozenset((token_second, token_end)))
2199
token_hour = Token(re.compile(r"(\d+)H"),
2200
datetime.timedelta(hours=1),
2201
frozenset((token_minute, token_end)))
2202
token_time = Token(re.compile(r"T"),
2204
frozenset((token_hour, token_minute,
2206
token_day = Token(re.compile(r"(\d+)D"),
2207
datetime.timedelta(days=1),
2208
frozenset((token_time, token_end)))
2209
token_month = Token(re.compile(r"(\d+)M"),
2210
datetime.timedelta(weeks=4),
2211
frozenset((token_day, token_end)))
2212
token_year = Token(re.compile(r"(\d+)Y"),
2213
datetime.timedelta(weeks=52),
2214
frozenset((token_month, token_end)))
2215
token_week = Token(re.compile(r"(\d+)W"),
2216
datetime.timedelta(weeks=1),
2217
frozenset((token_end, )))
2218
token_duration = Token(re.compile(r"P"), None,
2219
frozenset((token_year, token_month,
2220
token_day, token_time,
2222
# Define starting values
2223
value = datetime.timedelta() # Value so far
2225
followers = frozenset((token_duration, )) # Following valid tokens
2226
s = duration # String left to parse
2227
# Loop until end token is found
2228
while found_token is not token_end:
2229
# Search for any currently valid tokens
2230
for token in followers:
2231
match = token.regexp.match(s)
2232
if match is not None:
2234
if token.value is not None:
2235
# Value found, parse digits
2236
factor = int(match.group(1), 10)
2237
# Add to value so far
2238
value += factor * token.value
2239
# Strip token from string
2240
s = token.regexp.sub("", s, 1)
2243
# Set valid next tokens
2244
followers = found_token.followers
2247
# No currently valid tokens were found
2248
raise ValueError("Invalid RFC 3339 duration: {!r}"
2050
2254
def string_to_delta(interval):
2051
2255
"""Parse a string and return a datetime.timedelta
2145
2354
parser.add_argument("--no-dbus", action="store_false",
2146
2355
dest="use_dbus", help="Do not provide D-Bus"
2147
" system bus interface")
2356
" system bus interface", default=None)
2148
2357
parser.add_argument("--no-ipv6", action="store_false",
2149
dest="use_ipv6", help="Do not use IPv6")
2358
dest="use_ipv6", help="Do not use IPv6",
2150
2360
parser.add_argument("--no-restore", action="store_false",
2151
2361
dest="restore", help="Do not restore stored"
2362
" state", default=None)
2363
parser.add_argument("--socket", type=int,
2364
help="Specify a file descriptor to a network"
2365
" socket to use instead of creating one")
2153
2366
parser.add_argument("--statedir", metavar="DIR",
2154
2367
help="Directory to save/restore state in")
2368
parser.add_argument("--foreground", action="store_true",
2369
help="Run in foreground", default=None)
2370
parser.add_argument("--no-zeroconf", action="store_false",
2371
dest="zeroconf", help="Do not use Zeroconf",
2156
2374
options = parser.parse_args()
2158
2376
if options.check:
2378
fail_count, test_count = doctest.testmod()
2379
sys.exit(os.EX_OK if fail_count == 0 else 1)
2163
2381
# Default values for config file for server-global settings
2164
2382
server_defaults = { "interface": "",
2167
2385
"debug": "False",
2169
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
2387
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2388
":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2170
2389
"servicename": "Mandos",
2171
2390
"use_dbus": "True",
2172
2391
"use_ipv6": "True",
2173
2392
"debuglevel": "",
2174
2393
"restore": "True",
2175
"statedir": "/var/lib/mandos"
2395
"statedir": "/var/lib/mandos",
2396
"foreground": "False",
2178
2400
# Parse config file for server-global settings
2179
2401
server_config = configparser.SafeConfigParser(server_defaults)
2180
2402
del server_defaults
2181
server_config.read(os.path.join(options.configdir,
2403
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2183
2404
# Convert the SafeConfigParser object to a dict
2184
2405
server_settings = server_config.defaults()
2185
2406
# Use the appropriate methods on the non-string config options
2186
for option in ("debug", "use_dbus", "use_ipv6"):
2407
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
2187
2408
server_settings[option] = server_config.getboolean("DEFAULT",
2189
2410
if server_settings["port"]:
2190
2411
server_settings["port"] = server_config.getint("DEFAULT",
2413
if server_settings["socket"]:
2414
server_settings["socket"] = server_config.getint("DEFAULT",
2416
# Later, stdin will, and stdout and stderr might, be dup'ed
2417
# over with an opened os.devnull. But we don't want this to
2418
# happen with a supplied network socket.
2419
if 0 <= server_settings["socket"] <= 2:
2420
server_settings["socket"] = os.dup(server_settings
2192
2422
del server_config
2194
2424
# Override the settings from the config file with command line
2195
2425
# options, if set.
2196
2426
for option in ("interface", "address", "port", "debug",
2197
"priority", "servicename", "configdir",
2198
"use_dbus", "use_ipv6", "debuglevel", "restore",
2427
"priority", "servicename", "configdir", "use_dbus",
2428
"use_ipv6", "debuglevel", "restore", "statedir",
2429
"socket", "foreground", "zeroconf"):
2200
2430
value = getattr(options, option)
2201
2431
if value is not None:
2202
2432
server_settings[option] = value
2204
2434
# Force all strings to be unicode
2205
2435
for option in server_settings.keys():
2206
if type(server_settings[option]) is str:
2207
server_settings[option] = unicode(server_settings[option])
2436
if isinstance(server_settings[option], bytes):
2437
server_settings[option] = (server_settings[option]
2439
# Force all boolean options to be boolean
2440
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2441
"foreground", "zeroconf"):
2442
server_settings[option] = bool(server_settings[option])
2443
# Debug implies foreground
2444
if server_settings["debug"]:
2445
server_settings["foreground"] = True
2208
2446
# Now we have our good server settings in "server_settings"
2210
2448
##################################################################
2450
if (not server_settings["zeroconf"]
2451
and not (server_settings["port"]
2452
or server_settings["socket"] != "")):
2453
parser.error("Needs port or socket to work without Zeroconf")
2212
2455
# For convenience
2213
2456
debug = server_settings["debug"]
2214
2457
debuglevel = server_settings["debuglevel"]
2242
2486
global mandos_dbus_service
2243
2487
mandos_dbus_service = None
2245
tcp_server = MandosServer((server_settings["address"],
2246
server_settings["port"]),
2248
interface=(server_settings["interface"]
2252
server_settings["priority"],
2255
pidfilename = "/var/run/mandos.pid"
2490
if server_settings["socket"] != "":
2491
socketfd = server_settings["socket"]
2492
tcp_server = MandosServer(
2493
(server_settings["address"], server_settings["port"]),
2495
interface=(server_settings["interface"] or None),
2497
gnutls_priority=server_settings["priority"],
2501
pidfilename = "/run/mandos.pid"
2502
if not os.path.isdir("/run/."):
2503
pidfilename = "/var/run/mandos.pid"
2257
pidfile = open(pidfilename, "w")
2259
logger.error("Could not open file %r", pidfilename)
2506
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
2507
except IOError as e:
2508
logger.error("Could not open file %r", pidfilename,
2261
2511
for name in ("_mandos", "mandos", "nobody"):
2313
2565
bus_name = dbus.service.BusName("se.recompile.Mandos",
2314
bus, do_not_queue=True)
2315
old_bus_name = (dbus.service.BusName
2316
("se.bsnet.fukt.Mandos", bus,
2318
except dbus.exceptions.NameExistsException as e:
2319
logger.error(unicode(e) + ", disabling D-Bus")
2568
old_bus_name = dbus.service.BusName(
2569
"se.bsnet.fukt.Mandos", bus,
2571
except dbus.exceptions.DBusException as e:
2572
logger.error("Disabling D-Bus:", exc_info=e)
2320
2573
use_dbus = False
2321
2574
server_settings["use_dbus"] = False
2322
2575
tcp_server.use_dbus = False
2323
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2324
service = AvahiServiceToSyslog(name =
2325
server_settings["servicename"],
2326
servicetype = "_mandos._tcp",
2327
protocol = protocol, bus = bus)
2328
if server_settings["interface"]:
2329
service.interface = (if_nametoindex
2330
(str(server_settings["interface"])))
2577
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2578
service = AvahiServiceToSyslog(
2579
name = server_settings["servicename"],
2580
servicetype = "_mandos._tcp",
2581
protocol = protocol,
2583
if server_settings["interface"]:
2584
service.interface = if_nametoindex(
2585
server_settings["interface"].encode("utf-8"))
2332
2587
global multiprocessing_manager
2333
2588
multiprocessing_manager = multiprocessing.Manager()
2335
2590
client_class = Client
2337
client_class = functools.partial(ClientDBusTransitional,
2592
client_class = functools.partial(ClientDBus, bus = bus)
2340
2594
client_settings = Client.config_parser(client_config)
2341
2595
old_client_settings = {}
2342
2596
clients_data = {}
2598
# This is used to redirect stdout and stderr for checker processes
2600
wnull = open(os.devnull, "w") # A writable /dev/null
2601
# Only used if server is running in foreground but not in debug
2603
if debug or not foreground:
2344
2606
# Get client data and settings from last running state.
2345
2607
if server_settings["restore"]:
2347
2609
with open(stored_state_path, "rb") as stored_state:
2348
clients_data, old_client_settings = (pickle.load
2610
clients_data, old_client_settings = pickle.load(
2350
2612
os.remove(stored_state_path)
2351
2613
except IOError as e:
2352
logger.warning("Could not load persistent state: {0}"
2354
if e.errno != errno.ENOENT:
2614
if e.errno == errno.ENOENT:
2615
logger.warning("Could not load persistent state:"
2616
" {}".format(os.strerror(e.errno)))
2618
logger.critical("Could not load persistent state:",
2356
2621
except EOFError as e:
2357
2622
logger.warning("Could not load persistent state: "
2358
"EOFError: {0}".format(e))
2360
2626
with PGPEngine() as pgp:
2361
for client_name, client in clients_data.iteritems():
2627
for client_name, client in clients_data.items():
2628
# Skip removed clients
2629
if client_name not in client_settings:
2362
2632
# Decide which value to use after restoring saved state.
2363
2633
# We have three different values: Old config file,
2364
2634
# new config file, and saved state.
2385
2655
if datetime.datetime.utcnow() >= client["expires"]:
2386
2656
if not client["last_checked_ok"]:
2387
2657
logger.warning(
2388
"disabling client {0} - Client never "
2389
"performed a successful checker"
2390
.format(client_name))
2658
"disabling client {} - Client never "
2659
"performed a successful checker".format(
2391
2661
client["enabled"] = False
2392
2662
elif client["last_checker_status"] != 0:
2393
2663
logger.warning(
2394
"disabling client {0} - Client "
2395
"last checker failed with error code {1}"
2396
.format(client_name,
2397
client["last_checker_status"]))
2664
"disabling client {} - Client last"
2665
" checker failed with error code"
2668
client["last_checker_status"]))
2398
2669
client["enabled"] = False
2400
client["expires"] = (datetime.datetime
2402
+ client["timeout"])
2671
client["expires"] = (
2672
datetime.datetime.utcnow()
2673
+ client["timeout"])
2403
2674
logger.debug("Last checker succeeded,"
2404
" keeping {0} enabled"
2405
.format(client_name))
2675
" keeping {} enabled".format(
2407
client["secret"] = (
2408
pgp.decrypt(client["encrypted_secret"],
2409
client_settings[client_name]
2678
client["secret"] = pgp.decrypt(
2679
client["encrypted_secret"],
2680
client_settings[client_name]["secret"])
2411
2681
except PGPError:
2412
2682
# If decryption fails, we use secret from new settings
2413
logger.debug("Failed to decrypt {0} old secret"
2414
.format(client_name))
2415
client["secret"] = (
2416
client_settings[client_name]["secret"])
2683
logger.debug("Failed to decrypt {} old secret".format(
2685
client["secret"] = (client_settings[client_name]
2419
2688
# Add/remove clients based on new changes made to config
2420
2689
for client_name in (set(old_client_settings)
2423
2692
for client_name in (set(client_settings)
2424
2693
- set(old_client_settings)):
2425
2694
clients_data[client_name] = client_settings[client_name]
2427
2696
# Create all client objects
2428
for client_name, client in clients_data.iteritems():
2697
for client_name, client in clients_data.items():
2429
2698
tcp_server.clients[client_name] = client_class(
2430
name = client_name, settings = client)
2701
server_settings = server_settings)
2432
2703
if not tcp_server.clients:
2433
2704
logger.warning("No clients defined")
2439
pidfile.write(str(pid) + "\n".encode("utf-8"))
2442
logger.error("Could not write to file %r with PID %d",
2445
# "pidfile" was never created
2707
if pidfile is not None:
2711
print(pid, file=pidfile)
2713
logger.error("Could not write to file %r with PID %d",
2447
2716
del pidfilename
2448
signal.signal(signal.SIGINT, signal.SIG_IGN)
2450
2718
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2451
2719
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2723
@alternate_dbus_interfaces(
2724
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2454
2725
class MandosDBusService(DBusObjectWithProperties):
2455
2726
"""A D-Bus proxy object"""
2456
2728
def __init__(self):
2457
2729
dbus.service.Object.__init__(self, bus, "/")
2458
2731
_interface = "se.recompile.Mandos"
2460
2733
@dbus_interface_annotations(_interface)
2461
2734
def _foo(self):
2462
return { "org.freedesktop.DBus.Property"
2463
".EmitsChangedSignal":
2736
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2466
2739
@dbus.service.signal(_interface, signature="o")
2467
2740
def ClientAdded(self, objpath):