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
212
237
class AvahiError(Exception):
213
238
def __init__(self, value, *args, **kwargs):
214
239
self.value = value
215
super(AvahiError, self).__init__(value, *args, **kwargs)
216
def __unicode__(self):
217
return unicode(repr(self.value))
240
return super(AvahiError, self).__init__(value, *args,
219
244
class AvahiServiceError(AvahiError):
222
248
class AvahiGroupError(AvahiError):
434
466
runtime_expansions: Allowed attributes for runtime expansion.
435
467
expires: datetime.datetime(); time (UTC) when a client will be
436
468
disabled, or None
469
server_settings: The server_settings dict from main()
439
472
runtime_expansions = ("approval_delay", "approval_duration",
440
"created", "enabled", "fingerprint",
441
"host", "interval", "last_checked_ok",
473
"created", "enabled", "expires",
474
"fingerprint", "host", "interval",
475
"last_approval_request", "last_checked_ok",
442
476
"last_enabled", "name", "timeout")
443
client_defaults = { "timeout": "5m",
444
"extended_timeout": "15m",
446
"checker": "fping -q -- %%(host)s",
448
"approval_delay": "0s",
449
"approval_duration": "1s",
450
"approved_by_default": "True",
454
def timeout_milliseconds(self):
455
"Return the 'timeout' attribute in milliseconds"
456
return timedelta_to_milliseconds(self.timeout)
458
def extended_timeout_milliseconds(self):
459
"Return the 'extended_timeout' attribute in milliseconds"
460
return timedelta_to_milliseconds(self.extended_timeout)
462
def interval_milliseconds(self):
463
"Return the 'interval' attribute in milliseconds"
464
return timedelta_to_milliseconds(self.interval)
466
def approval_delay_milliseconds(self):
467
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",
470
490
def config_parser(config):
680
703
self.current_checker_command)
681
704
# Start a new checker if needed
682
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 }
684
# In case checker_command has exactly one % operator
685
command = self.checker_command % self.host
687
# Escape attributes for the shell
688
escaped_attrs = dict(
690
re.escape(unicode(str(getattr(self, attr, "")),
694
self.runtime_expansions)
697
command = self.checker_command % escaped_attrs
698
except TypeError as error:
699
logger.error('Could not format string "%s"',
700
self.checker_command, exc_info=error)
701
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
702
717
self.current_checker_command = command
704
logger.info("Starting checker %r for %s",
719
logger.info("Starting checker %r for %s", command,
706
721
# We don't need to redirect stdout and stderr, since
707
722
# in normal mode, that is already done by daemon(),
708
723
# and in debug mode we don't want to. (Stdin is
709
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,
710
733
self.checker = subprocess.Popen(command,
713
self.checker_callback_tag = (gobject.child_watch_add
715
self.checker_callback,
717
# The checker may have completed before the gobject
718
# 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.
719
747
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
721
gobject.source_remove(self.checker_callback_tag)
722
self.checker_callback(pid, status, command)
723
748
except OSError as error:
724
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)
726
758
# Re-run this periodically if run by gobject.timeout_add
846
885
If called like _is_dbus_thing("method") it returns a function
847
886
suitable for use as predicate to inspect.getmembers().
849
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
888
return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
852
891
def _get_all_dbus_things(self, thing):
853
892
"""Returns a generator of (name, attribute) pairs
855
return ((getattr(athing.__get__(self), "_dbus_name",
894
return ((getattr(athing.__get__(self), "_dbus_name", name),
857
895
athing.__get__(self))
858
896
for cls in self.__class__.__mro__
859
897
for name, athing in
860
inspect.getmembers(cls,
861
self._is_dbus_thing(thing)))
898
inspect.getmembers(cls, self._is_dbus_thing(thing)))
863
900
def _get_dbus_property(self, interface_name, property_name):
864
901
"""Returns a bound method if one exists which is a D-Bus
865
902
property with the specified name and interface.
867
for cls in self.__class__.__mro__:
868
for name, value in (inspect.getmembers
870
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")):
871
907
if (value._dbus_name == property_name
872
908
and value._dbus_interface == interface_name):
873
909
return value.__get__(self)
875
911
# No such property
876
raise DBusPropertyNotFound(self.dbus_object_path + ":"
877
+ interface_name + "."
912
raise DBusPropertyNotFound("{}:{}.{}".format(
913
self.dbus_object_path, interface_name, property_name))
880
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
915
@dbus.service.method(dbus.PROPERTIES_IFACE,
881
917
out_signature="v")
882
918
def Get(self, interface_name, property_name):
883
919
"""Standard D-Bus property Get() method, see D-Bus standard.
1013
1060
return xmlstring
1016
def datetime_to_dbus (dt, variant_level=0):
1063
def datetime_to_dbus(dt, variant_level=0):
1017
1064
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1019
1066
return dbus.String("", variant_level = variant_level)
1020
return dbus.String(dt.isoformat(),
1021
variant_level=variant_level)
1024
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
1026
"""Applied to an empty subclass of a D-Bus object, this metaclass
1027
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).
1029
def __new__(mcs, name, bases, attr):
1030
# Go through all the base classes which could have D-Bus
1031
# methods, signals, or properties in them
1032
old_interface_names = []
1033
for base in (b for b in bases
1034
if issubclass(b, dbus.service.Object)):
1035
# Go though all attributes of the base class
1036
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):
1037
1101
# Ignore non-D-Bus attributes, and D-Bus attributes
1038
1102
# with the wrong interface name
1039
1103
if (not hasattr(attribute, "_dbus_interface")
1040
or not attribute._dbus_interface
1041
.startswith("se.recompile.Mandos")):
1104
or not attribute._dbus_interface.startswith(
1105
orig_interface_name)):
1043
1107
# Create an alternate D-Bus interface name based on
1044
1108
# the current name
1045
alt_interface = (attribute._dbus_interface
1046
.replace("se.recompile.Mandos",
1047
"se.bsnet.fukt.Mandos"))
1048
if alt_interface != attribute._dbus_interface:
1049
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)
1050
1112
# Is this a D-Bus signal?
1051
1113
if getattr(attribute, "_dbus_is_signal", False):
1052
# Extract the original non-method function by
1114
# Extract the original non-method undecorated
1115
# function by black magic
1054
1116
nonmethod_func = (dict(
1055
zip(attribute.func_code.co_freevars,
1056
attribute.__closure__))["func"]
1117
zip(attribute.func_code.co_freevars,
1118
attribute.__closure__))
1119
["func"].cell_contents)
1058
1120
# Create a new, but exactly alike, function
1059
1121
# object, and decorate it to be a new D-Bus signal
1060
1122
# with the alternate D-Bus interface name
1061
new_function = (dbus.service.signal
1063
attribute._dbus_signature)
1123
new_function = (dbus.service.signal(
1124
alt_interface, attribute._dbus_signature)
1064
1125
(types.FunctionType(
1065
nonmethod_func.func_code,
1066
nonmethod_func.func_globals,
1067
nonmethod_func.func_name,
1068
nonmethod_func.func_defaults,
1069
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)))
1070
1131
# Copy annotations, if any
1072
new_function._dbus_annotations = (
1073
dict(attribute._dbus_annotations))
1133
new_function._dbus_annotations = dict(
1134
attribute._dbus_annotations)
1074
1135
except AttributeError:
1076
1137
# Define a creator of a function to call both the
1077
# old and new functions, so both the old and new
1078
# 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
1079
1141
def fixscope(func1, func2):
1080
1142
"""This function is a scope container to pass
1081
1143
func1 and func2 to the "call_both" function
1082
1144
outside of its arguments"""
1083
1146
def call_both(*args, **kwargs):
1084
1147
"""This function will emit two D-Bus
1085
1148
signals by calling func1 and func2"""
1086
1149
func1(*args, **kwargs)
1087
1150
func2(*args, **kwargs)
1088
1152
return call_both
1089
1153
# Create the "call_both" function and add it to
1091
attr[attrname] = fixscope(attribute,
1155
attr[attrname] = fixscope(attribute, new_function)
1093
1156
# Is this a D-Bus method?
1094
1157
elif getattr(attribute, "_dbus_is_method", False):
1095
1158
# Create a new, but exactly alike, function
1096
1159
# object. Decorate it to be a new D-Bus method
1097
1160
# with the alternate D-Bus interface name. Add it
1098
1161
# to the class.
1099
attr[attrname] = (dbus.service.method
1101
attribute._dbus_in_signature,
1102
attribute._dbus_out_signature)
1104
(attribute.func_code,
1105
attribute.func_globals,
1106
attribute.func_name,
1107
attribute.func_defaults,
1108
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)))
1109
1172
# Copy annotations, if any
1111
attr[attrname]._dbus_annotations = (
1112
dict(attribute._dbus_annotations))
1174
attr[attrname]._dbus_annotations = dict(
1175
attribute._dbus_annotations)
1113
1176
except AttributeError:
1115
1178
# Is this a D-Bus property?
1143
1204
# object. Decorate it to be a new D-Bus interface
1144
1205
# with the alternate D-Bus interface name. Add it
1145
1206
# to the class.
1146
attr[attrname] = (dbus_interface_annotations
1149
(attribute.func_code,
1150
attribute.func_globals,
1151
attribute.func_name,
1152
attribute.func_defaults,
1153
attribute.func_closure)))
1154
# Deprecate all old interfaces
1155
iname="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1156
for old_interface_name in old_interface_names:
1157
@dbus_interface_annotations(old_interface_name)
1159
return { "org.freedesktop.DBus.Deprecated": "true" }
1160
# Find an unused name
1161
for aname in (iname.format(i) for i in itertools.count()):
1162
if aname not in attr:
1165
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"})
1168
1241
class ClientDBus(Client, DBusObjectWithProperties):
1169
1242
"""A Client class using D-Bus
1237
1325
datetime_to_dbus, "LastApprovalRequest")
1238
1326
approved_by_default = notifychangeproperty(dbus.Boolean,
1239
1327
"ApprovedByDefault")
1240
approval_delay = notifychangeproperty(dbus.UInt64,
1243
timedelta_to_milliseconds)
1328
approval_delay = notifychangeproperty(
1329
dbus.UInt64, "ApprovalDelay",
1330
type_func = lambda td: td.total_seconds() * 1000)
1244
1331
approval_duration = notifychangeproperty(
1245
1332
dbus.UInt64, "ApprovalDuration",
1246
type_func = timedelta_to_milliseconds)
1333
type_func = lambda td: td.total_seconds() * 1000)
1247
1334
host = notifychangeproperty(dbus.String, "Host")
1248
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1250
timedelta_to_milliseconds)
1335
timeout = notifychangeproperty(
1336
dbus.UInt64, "Timeout",
1337
type_func = lambda td: td.total_seconds() * 1000)
1251
1338
extended_timeout = notifychangeproperty(
1252
1339
dbus.UInt64, "ExtendedTimeout",
1253
type_func = timedelta_to_milliseconds)
1254
interval = notifychangeproperty(dbus.UInt64,
1257
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)
1258
1344
checker_command = notifychangeproperty(dbus.String, "Checker")
1345
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1346
invalidate_only=True)
1260
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
1790
1872
def fingerprint(openpgp):
1791
1873
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1792
1874
# New GnuTLS "datum" with the OpenPGP public key
1793
datum = (gnutls.library.types
1794
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1797
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)))
1798
1879
# New empty GnuTLS certificate
1799
1880
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1800
(gnutls.library.functions
1801
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1881
gnutls.library.functions.gnutls_openpgp_crt_init(
1802
1883
# Import the OpenPGP public key into the certificate
1803
(gnutls.library.functions
1804
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1805
gnutls.library.constants
1806
.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)
1807
1887
# Verify the self signature in the key
1808
1888
crtverify = ctypes.c_uint()
1809
(gnutls.library.functions
1810
.gnutls_openpgp_crt_verify_self(crt, 0,
1811
ctypes.byref(crtverify)))
1889
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
crt, 0, ctypes.byref(crtverify))
1812
1891
if crtverify.value != 0:
1813
1892
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1814
raise (gnutls.errors.CertificateSecurityError
1893
raise gnutls.errors.CertificateSecurityError(
1816
1895
# New buffer for the fingerprint
1817
1896
buf = ctypes.create_string_buffer(20)
1818
1897
buf_len = ctypes.c_size_t()
1819
1898
# Get the fingerprint from the certificate into the buffer
1820
(gnutls.library.functions
1821
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1822
ctypes.byref(buf_len)))
1899
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1823
1901
# Deinit the certificate
1824
1902
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1825
1903
# Convert the buffer to a Python bytestring
1875
1954
interface: None or a network interface name (string)
1876
1955
use_ipv6: Boolean; to use IPv6 or not
1878
1958
def __init__(self, server_address, RequestHandlerClass,
1879
interface=None, use_ipv6=True):
1962
"""If socketfd is set, use that file descriptor instead of
1963
creating a new one with socket.socket().
1880
1965
self.interface = interface
1882
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.
1883
1994
socketserver.TCPServer.__init__(self, server_address,
1884
1995
RequestHandlerClass)
1885
1997
def server_bind(self):
1886
1998
"""This overrides the normal server_bind() function
1887
1999
to bind to an interface if one was specified, and also NOT to
1962
2081
def add_pipe(self, parent_pipe, proc):
1963
2082
# Call "handle_ipc" for both data and EOF events
1964
gobject.io_add_watch(parent_pipe.fileno(),
1965
gobject.IO_IN | gobject.IO_HUP,
1966
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,
1971
def handle_ipc(self, source, condition, parent_pipe=None,
1972
proc = None, client_object=None):
1974
gobject.IO_IN: "IN", # There is data to read.
1975
gobject.IO_OUT: "OUT", # Data can be written (without
1977
gobject.IO_PRI: "PRI", # There is urgent data to read.
1978
gobject.IO_ERR: "ERR", # Error condition.
1979
gobject.IO_HUP: "HUP" # Hung up (the connection has been
1980
# broken, usually for pipes and
1983
conditions_string = ' | '.join(name
1985
condition_names.iteritems()
1986
if cond & condition)
2090
def handle_ipc(self, source, condition,
2093
client_object=None):
1987
2094
# error, or the other end of multiprocessing.Pipe has closed
1988
if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
2095
if condition & (gobject.IO_ERR | gobject.IO_HUP):
1989
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
2187
# "value" is not None,
2188
# must have a "group"
2190
"value", # datetime.timedelta or
2192
"followers")) # Tokens valid after
2194
Token = collections.namedtuple("Token", (
2195
"regexp", # To match token; if "value" is not None, must have
2196
# a "group" containing digits
2197
"value", # datetime.timedelta or None
2198
"followers")) # Tokens valid after this token
2199
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2200
# the "duration" ABNF definition in RFC 3339, Appendix A.
2201
token_end = Token(re.compile(r"$"), None, frozenset())
2202
token_second = Token(re.compile(r"(\d+)S"),
2203
datetime.timedelta(seconds=1),
2204
frozenset((token_end, )))
2205
token_minute = Token(re.compile(r"(\d+)M"),
2206
datetime.timedelta(minutes=1),
2207
frozenset((token_second, token_end)))
2208
token_hour = Token(re.compile(r"(\d+)H"),
2209
datetime.timedelta(hours=1),
2210
frozenset((token_minute, token_end)))
2211
token_time = Token(re.compile(r"T"),
2213
frozenset((token_hour, token_minute,
2215
token_day = Token(re.compile(r"(\d+)D"),
2216
datetime.timedelta(days=1),
2217
frozenset((token_time, token_end)))
2218
token_month = Token(re.compile(r"(\d+)M"),
2219
datetime.timedelta(weeks=4),
2220
frozenset((token_day, token_end)))
2221
token_year = Token(re.compile(r"(\d+)Y"),
2222
datetime.timedelta(weeks=52),
2223
frozenset((token_month, token_end)))
2224
token_week = Token(re.compile(r"(\d+)W"),
2225
datetime.timedelta(weeks=1),
2226
frozenset((token_end, )))
2227
token_duration = Token(re.compile(r"P"), None,
2228
frozenset((token_year, token_month,
2229
token_day, token_time,
2231
# Define starting values
2232
value = datetime.timedelta() # Value so far
2234
followers = frozenset((token_duration,)) # Following valid tokens
2235
s = duration # String left to parse
2236
# Loop until end token is found
2237
while found_token is not token_end:
2238
# Search for any currently valid tokens
2239
for token in followers:
2240
match = token.regexp.match(s)
2241
if match is not None:
2243
if token.value is not None:
2244
# Value found, parse digits
2245
factor = int(match.group(1), 10)
2246
# Add to value so far
2247
value += factor * token.value
2248
# Strip token from string
2249
s = token.regexp.sub("", s, 1)
2252
# Set valid next tokens
2253
followers = found_token.followers
2256
# No currently valid tokens were found
2257
raise ValueError("Invalid RFC 3339 duration: {!r}"
2052
2263
def string_to_delta(interval):
2053
2264
"""Parse a string and return a datetime.timedelta
2147
2363
parser.add_argument("--no-dbus", action="store_false",
2148
2364
dest="use_dbus", help="Do not provide D-Bus"
2149
" system bus interface")
2365
" system bus interface", default=None)
2150
2366
parser.add_argument("--no-ipv6", action="store_false",
2151
dest="use_ipv6", help="Do not use IPv6")
2367
dest="use_ipv6", help="Do not use IPv6",
2152
2369
parser.add_argument("--no-restore", action="store_false",
2153
2370
dest="restore", help="Do not restore stored"
2371
" state", default=None)
2372
parser.add_argument("--socket", type=int,
2373
help="Specify a file descriptor to a network"
2374
" socket to use instead of creating one")
2155
2375
parser.add_argument("--statedir", metavar="DIR",
2156
2376
help="Directory to save/restore state in")
2377
parser.add_argument("--foreground", action="store_true",
2378
help="Run in foreground", default=None)
2379
parser.add_argument("--no-zeroconf", action="store_false",
2380
dest="zeroconf", help="Do not use Zeroconf",
2158
2383
options = parser.parse_args()
2160
2385
if options.check:
2387
fail_count, test_count = doctest.testmod()
2388
sys.exit(os.EX_OK if fail_count == 0 else 1)
2165
2390
# Default values for config file for server-global settings
2166
2391
server_defaults = { "interface": "",
2169
2394
"debug": "False",
2171
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
2396
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2397
":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2172
2398
"servicename": "Mandos",
2173
2399
"use_dbus": "True",
2174
2400
"use_ipv6": "True",
2175
2401
"debuglevel": "",
2176
2402
"restore": "True",
2177
"statedir": "/var/lib/mandos"
2404
"statedir": "/var/lib/mandos",
2405
"foreground": "False",
2180
2409
# Parse config file for server-global settings
2181
2410
server_config = configparser.SafeConfigParser(server_defaults)
2182
2411
del server_defaults
2183
server_config.read(os.path.join(options.configdir,
2412
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2185
2413
# Convert the SafeConfigParser object to a dict
2186
2414
server_settings = server_config.defaults()
2187
2415
# Use the appropriate methods on the non-string config options
2188
for option in ("debug", "use_dbus", "use_ipv6"):
2416
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
2189
2417
server_settings[option] = server_config.getboolean("DEFAULT",
2191
2419
if server_settings["port"]:
2192
2420
server_settings["port"] = server_config.getint("DEFAULT",
2422
if server_settings["socket"]:
2423
server_settings["socket"] = server_config.getint("DEFAULT",
2425
# Later, stdin will, and stdout and stderr might, be dup'ed
2426
# over with an opened os.devnull. But we don't want this to
2427
# happen with a supplied network socket.
2428
if 0 <= server_settings["socket"] <= 2:
2429
server_settings["socket"] = os.dup(server_settings
2194
2431
del server_config
2196
2433
# Override the settings from the config file with command line
2197
2434
# options, if set.
2198
2435
for option in ("interface", "address", "port", "debug",
2199
"priority", "servicename", "configdir",
2200
"use_dbus", "use_ipv6", "debuglevel", "restore",
2436
"priority", "servicename", "configdir", "use_dbus",
2437
"use_ipv6", "debuglevel", "restore", "statedir",
2438
"socket", "foreground", "zeroconf"):
2202
2439
value = getattr(options, option)
2203
2440
if value is not None:
2204
2441
server_settings[option] = value
2206
2443
# Force all strings to be unicode
2207
2444
for option in server_settings.keys():
2208
if type(server_settings[option]) is str:
2209
server_settings[option] = unicode(server_settings[option])
2445
if isinstance(server_settings[option], bytes):
2446
server_settings[option] = (server_settings[option]
2448
# Force all boolean options to be boolean
2449
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2450
"foreground", "zeroconf"):
2451
server_settings[option] = bool(server_settings[option])
2452
# Debug implies foreground
2453
if server_settings["debug"]:
2454
server_settings["foreground"] = True
2210
2455
# Now we have our good server settings in "server_settings"
2212
2457
##################################################################
2459
if (not server_settings["zeroconf"]
2460
and not (server_settings["port"]
2461
or server_settings["socket"] != "")):
2462
parser.error("Needs port or socket to work without Zeroconf")
2214
2464
# For convenience
2215
2465
debug = server_settings["debug"]
2216
2466
debuglevel = server_settings["debuglevel"]
2316
2574
bus_name = dbus.service.BusName("se.recompile.Mandos",
2317
bus, do_not_queue=True)
2318
old_bus_name = (dbus.service.BusName
2319
("se.bsnet.fukt.Mandos", bus,
2321
except dbus.exceptions.NameExistsException as e:
2577
old_bus_name = dbus.service.BusName(
2578
"se.bsnet.fukt.Mandos", bus,
2580
except dbus.exceptions.DBusException as e:
2322
2581
logger.error("Disabling D-Bus:", exc_info=e)
2323
2582
use_dbus = False
2324
2583
server_settings["use_dbus"] = False
2325
2584
tcp_server.use_dbus = False
2326
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2327
service = AvahiServiceToSyslog(name =
2328
server_settings["servicename"],
2329
servicetype = "_mandos._tcp",
2330
protocol = protocol, bus = bus)
2331
if server_settings["interface"]:
2332
service.interface = (if_nametoindex
2333
(str(server_settings["interface"])))
2586
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2587
service = AvahiServiceToSyslog(
2588
name = server_settings["servicename"],
2589
servicetype = "_mandos._tcp",
2590
protocol = protocol,
2592
if server_settings["interface"]:
2593
service.interface = if_nametoindex(
2594
server_settings["interface"].encode("utf-8"))
2335
2596
global multiprocessing_manager
2336
2597
multiprocessing_manager = multiprocessing.Manager()
2338
2599
client_class = Client
2340
client_class = functools.partial(ClientDBusTransitional,
2601
client_class = functools.partial(ClientDBus, bus = bus)
2343
2603
client_settings = Client.config_parser(client_config)
2344
2604
old_client_settings = {}
2345
2605
clients_data = {}
2607
# This is used to redirect stdout and stderr for checker processes
2609
wnull = open(os.devnull, "w") # A writable /dev/null
2610
# Only used if server is running in foreground but not in debug
2612
if debug or not foreground:
2347
2615
# Get client data and settings from last running state.
2348
2616
if server_settings["restore"]:
2350
2618
with open(stored_state_path, "rb") as stored_state:
2351
clients_data, old_client_settings = (pickle.load
2619
clients_data, old_client_settings = pickle.load(
2353
2621
os.remove(stored_state_path)
2354
2622
except IOError as e:
2355
2623
if e.errno == errno.ENOENT:
2356
logger.warning("Could not load persistent state: {0}"
2357
.format(os.strerror(e.errno)))
2624
logger.warning("Could not load persistent state:"
2625
" {}".format(os.strerror(e.errno)))
2359
2627
logger.critical("Could not load persistent state:",
2362
2630
except EOFError as e:
2363
2631
logger.warning("Could not load persistent state: "
2364
"EOFError:", exc_info=e)
2366
2635
with PGPEngine() as pgp:
2367
for client_name, client in clients_data.iteritems():
2636
for client_name, client in clients_data.items():
2637
# Skip removed clients
2638
if client_name not in client_settings:
2368
2641
# Decide which value to use after restoring saved state.
2369
2642
# We have three different values: Old config file,
2370
2643
# new config file, and saved state.
2391
2664
if datetime.datetime.utcnow() >= client["expires"]:
2392
2665
if not client["last_checked_ok"]:
2393
2666
logger.warning(
2394
"disabling client {0} - Client never "
2395
"performed a successful checker"
2396
.format(client_name))
2667
"disabling client {} - Client never "
2668
"performed a successful checker".format(
2397
2670
client["enabled"] = False
2398
2671
elif client["last_checker_status"] != 0:
2399
2672
logger.warning(
2400
"disabling client {0} - Client "
2401
"last checker failed with error code {1}"
2402
.format(client_name,
2403
client["last_checker_status"]))
2673
"disabling client {} - Client last"
2674
" checker failed with error code"
2677
client["last_checker_status"]))
2404
2678
client["enabled"] = False
2406
client["expires"] = (datetime.datetime
2408
+ client["timeout"])
2680
client["expires"] = (
2681
datetime.datetime.utcnow()
2682
+ client["timeout"])
2409
2683
logger.debug("Last checker succeeded,"
2410
" keeping {0} enabled"
2411
.format(client_name))
2684
" keeping {} enabled".format(
2413
client["secret"] = (
2414
pgp.decrypt(client["encrypted_secret"],
2415
client_settings[client_name]
2687
client["secret"] = pgp.decrypt(
2688
client["encrypted_secret"],
2689
client_settings[client_name]["secret"])
2417
2690
except PGPError:
2418
2691
# If decryption fails, we use secret from new settings
2419
logger.debug("Failed to decrypt {0} old secret"
2420
.format(client_name))
2421
client["secret"] = (
2422
client_settings[client_name]["secret"])
2692
logger.debug("Failed to decrypt {} old secret".format(
2694
client["secret"] = (client_settings[client_name]
2424
2697
# Add/remove clients based on new changes made to config
2425
2698
for client_name in (set(old_client_settings)
2430
2703
clients_data[client_name] = client_settings[client_name]
2432
2705
# Create all client objects
2433
for client_name, client in clients_data.iteritems():
2706
for client_name, client in clients_data.items():
2434
2707
tcp_server.clients[client_name] = client_class(
2435
name = client_name, settings = client)
2710
server_settings = server_settings)
2437
2712
if not tcp_server.clients:
2438
2713
logger.warning("No clients defined")
2444
pidfile.write(str(pid) + "\n".encode("utf-8"))
2447
logger.error("Could not write to file %r with PID %d",
2450
# "pidfile" was never created
2716
if pidfile is not None:
2720
print(pid, file=pidfile)
2722
logger.error("Could not write to file %r with PID %d",
2452
2725
del pidfilename
2453
signal.signal(signal.SIGINT, signal.SIG_IGN)
2455
2727
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2456
2728
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2732
@alternate_dbus_interfaces(
2733
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2459
2734
class MandosDBusService(DBusObjectWithProperties):
2460
2735
"""A D-Bus proxy object"""
2461
2737
def __init__(self):
2462
2738
dbus.service.Object.__init__(self, bus, "/")
2463
2740
_interface = "se.recompile.Mandos"
2465
2742
@dbus_interface_annotations(_interface)
2466
2743
def _foo(self):
2467
return { "org.freedesktop.DBus.Property"
2468
".EmitsChangedSignal":
2745
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2471
2748
@dbus.service.signal(_interface, signature="o")
2472
2749
def ClientAdded(self, objpath):