11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2015 Teddy Hogeborn
15
# Copyright © 2008-2015 Björn Påhlsson
14
# Copyright © 2008-2013 Teddy Hogeborn
15
# Copyright © 2008-2013 Björn Påhlsson
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
88
88
except ImportError:
89
89
SO_BINDTODEVICE = None
91
if sys.version_info.major == 2:
95
92
stored_state_file = "clients.pickle"
97
94
logger = logging.getLogger()
95
syslogger = (logging.handlers.SysLogHandler
96
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
97
address = str("/dev/log")))
101
if_nametoindex = ctypes.cdll.LoadLibrary(
102
ctypes.util.find_library("c")).if_nametoindex
100
if_nametoindex = (ctypes.cdll.LoadLibrary
101
(ctypes.util.find_library("c"))
103
103
except (OSError, AttributeError):
105
104
def if_nametoindex(interface):
106
105
"Get an interface index the hard way, i.e. using fcntl()"
107
106
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
108
107
with contextlib.closing(socket.socket()) as s:
109
108
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
struct.pack(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
112
113
return interface_index
115
116
def initlogger(debug, level=logging.WARNING):
116
117
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler(
120
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
address = "/dev/log"))
122
119
syslogger.setFormatter(logging.Formatter
123
120
('Mandos [%(process)d]: %(levelname)s:'
187
183
def encrypt(self, data, password):
188
184
passphrase = self.password_encode(password)
189
with tempfile.NamedTemporaryFile(
190
dir=self.tempdir) as passfile:
185
with tempfile.NamedTemporaryFile(dir=self.tempdir
191
187
passfile.write(passphrase)
193
189
proc = subprocess.Popen(['gpg', '--symmetric',
205
201
def decrypt(self, data, password):
206
202
passphrase = self.password_encode(password)
207
with tempfile.NamedTemporaryFile(
208
dir = self.tempdir) as passfile:
203
with tempfile.NamedTemporaryFile(dir = self.tempdir
209
205
passfile.write(passphrase)
211
207
proc = subprocess.Popen(['gpg', '--decrypt',
224
221
class AvahiError(Exception):
225
222
def __init__(self, value, *args, **kwargs):
226
223
self.value = value
227
return super(AvahiError, self).__init__(value, *args,
224
super(AvahiError, self).__init__(value, *args, **kwargs)
225
def __unicode__(self):
226
return unicode(repr(self.value))
231
228
class AvahiServiceError(AvahiError):
235
231
class AvahiGroupError(AvahiError):
257
253
bus: dbus.SystemBus()
261
interface = avahi.IF_UNSPEC,
269
protocol = avahi.PROTO_UNSPEC,
256
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
257
servicetype = None, port = None, TXT = None,
258
domain = "", host = "", max_renames = 32768,
259
protocol = avahi.PROTO_UNSPEC, bus = None):
271
260
self.interface = interface
273
262
self.type = servicetype
284
273
self.entry_group_state_changed_match = None
286
def rename(self, remove=True):
287
276
"""Derived from the Avahi example code"""
288
277
if self.rename_count >= self.max_renames:
289
278
logger.critical("No suitable Zeroconf service name found"
290
279
" after %i retries, exiting.",
291
280
self.rename_count)
292
281
raise AvahiServiceError("Too many renames")
294
self.server.GetAlternativeServiceName(self.name))
295
self.rename_count += 1
282
self.name = unicode(self.server
283
.GetAlternativeServiceName(self.name))
296
284
logger.info("Changing Zeroconf service name to %r ...",
302
289
except dbus.exceptions.DBusException as error:
303
if (error.get_dbus_name()
304
== "org.freedesktop.Avahi.CollisionError"):
305
logger.info("Local Zeroconf service name collision.")
306
return self.rename(remove=False)
308
logger.critical("D-Bus Exception", exc_info=error)
290
logger.critical("D-Bus Exception", exc_info=error)
293
self.rename_count += 1
312
295
def remove(self):
313
296
"""Derived from the Avahi example code"""
368
352
def server_state_changed(self, state, error=None):
369
353
"""Derived from the Avahi example code"""
370
354
logger.debug("Avahi server state change: %i", state)
372
avahi.SERVER_INVALID: "Zeroconf server invalid",
373
avahi.SERVER_REGISTERING: None,
374
avahi.SERVER_COLLISION: "Zeroconf server name collision",
375
avahi.SERVER_FAILURE: "Zeroconf server failure",
355
bad_states = { avahi.SERVER_INVALID:
356
"Zeroconf server invalid",
357
avahi.SERVER_REGISTERING: None,
358
avahi.SERVER_COLLISION:
359
"Zeroconf server name collision",
360
avahi.SERVER_FAILURE:
361
"Zeroconf server failure" }
377
362
if state in bad_states:
378
363
if bad_states[state] is not None:
379
364
if error is None:
398
383
follow_name_owner_changes=True),
399
384
avahi.DBUS_INTERFACE_SERVER)
400
385
self.server.connect_to_signal("StateChanged",
401
self.server_state_changed)
386
self.server_state_changed)
402
387
self.server_state_changed(self.server.GetState())
405
390
class AvahiServiceToSyslog(AvahiService):
406
def rename(self, *args, **kwargs):
407
392
"""Add the new name to the syslog messages"""
408
ret = AvahiService.rename(self, *args, **kwargs)
409
syslogger.setFormatter(logging.Formatter(
410
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
393
ret = AvahiService.rename(self)
394
syslogger.setFormatter(logging.Formatter
395
('Mandos ({0}) [%(process)d]:'
396
' %(levelname)s: %(message)s'
401
def timedelta_to_milliseconds(td):
402
"Convert a datetime.timedelta() to milliseconds"
403
return ((td.days * 24 * 60 * 60 * 1000)
404
+ (td.seconds * 1000)
405
+ (td.microseconds // 1000))
415
408
class Client(object):
416
409
"""A representation of a client host served by this server.
461
454
"fingerprint", "host", "interval",
462
455
"last_approval_request", "last_checked_ok",
463
456
"last_enabled", "name", "timeout")
466
"extended_timeout": "PT15M",
468
"checker": "fping -q -- %%(host)s",
470
"approval_delay": "PT0S",
471
"approval_duration": "PT1S",
472
"approved_by_default": "True",
457
client_defaults = { "timeout": "PT5M",
458
"extended_timeout": "PT15M",
460
"checker": "fping -q -- %%(host)s",
462
"approval_delay": "PT0S",
463
"approval_duration": "PT1S",
464
"approved_by_default": "True",
468
def timeout_milliseconds(self):
469
"Return the 'timeout' attribute in milliseconds"
470
return timedelta_to_milliseconds(self.timeout)
472
def extended_timeout_milliseconds(self):
473
"Return the 'extended_timeout' attribute in milliseconds"
474
return timedelta_to_milliseconds(self.extended_timeout)
476
def interval_milliseconds(self):
477
"Return the 'interval' attribute in milliseconds"
478
return timedelta_to_milliseconds(self.interval)
480
def approval_delay_milliseconds(self):
481
return timedelta_to_milliseconds(self.approval_delay)
477
484
def config_parser(config):
543
547
self.expires = None
545
549
logger.debug("Creating client %r", self.name)
550
# Uppercase and remove spaces from fingerprint for later
551
# comparison purposes with return value from the fingerprint()
546
553
logger.debug(" Fingerprint: %s", self.fingerprint)
547
554
self.created = settings.get("created",
548
555
datetime.datetime.utcnow())
555
562
self.current_checker_command = None
556
563
self.approved = None
557
564
self.approvals_pending = 0
558
self.changedstate = multiprocessing_manager.Condition(
559
multiprocessing_manager.Lock())
560
self.client_structure = [attr
561
for attr in self.__dict__.iterkeys()
565
self.changedstate = (multiprocessing_manager
566
.Condition(multiprocessing_manager
568
self.client_structure = [attr for attr in
569
self.__dict__.iterkeys()
562
570
if not attr.startswith("_")]
563
571
self.client_structure.append("client_structure")
565
for name, t in inspect.getmembers(
566
type(self), lambda obj: isinstance(obj, property)):
573
for name, t in inspect.getmembers(type(self),
567
577
if not name.startswith("_"):
568
578
self.client_structure.append(name)
611
621
# and every interval from then on.
612
622
if self.checker_initiator_tag is not None:
613
623
gobject.source_remove(self.checker_initiator_tag)
614
self.checker_initiator_tag = gobject.timeout_add(
615
int(self.interval.total_seconds() * 1000),
624
self.checker_initiator_tag = (gobject.timeout_add
625
(self.interval_milliseconds(),
617
627
# Schedule a disable() when 'timeout' has passed
618
628
if self.disable_initiator_tag is not None:
619
629
gobject.source_remove(self.disable_initiator_tag)
620
self.disable_initiator_tag = gobject.timeout_add(
621
int(self.timeout.total_seconds() * 1000), self.disable)
630
self.disable_initiator_tag = (gobject.timeout_add
631
(self.timeout_milliseconds(),
622
633
# Also start a new checker *right now*.
623
634
self.start_checker()
653
665
gobject.source_remove(self.disable_initiator_tag)
654
666
self.disable_initiator_tag = None
655
667
if getattr(self, "enabled", False):
656
self.disable_initiator_tag = gobject.timeout_add(
657
int(timeout.total_seconds() * 1000), self.disable)
668
self.disable_initiator_tag = (gobject.timeout_add
669
(timedelta_to_milliseconds
670
(timeout), self.disable))
658
671
self.expires = datetime.datetime.utcnow() + timeout
660
673
def need_approval(self):
677
690
# If a checker exists, make sure it is not a zombie
679
692
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
680
except AttributeError:
682
except OSError as error:
683
if error.errno != errno.ECHILD:
693
except (AttributeError, OSError) as error:
694
if (isinstance(error, OSError)
695
and error.errno != errno.ECHILD):
687
699
logger.warning("Checker was a zombie")
691
703
# Start a new checker if needed
692
704
if self.checker is None:
693
705
# Escape attributes for the shell
695
attr: re.escape(str(getattr(self, attr)))
696
for attr in self.runtime_expansions }
706
escaped_attrs = dict(
707
(attr, re.escape(unicode(getattr(self, attr))))
709
self.runtime_expansions)
698
711
command = self.checker_command % escaped_attrs
699
712
except TypeError as error:
700
713
logger.error('Could not format string "%s"',
701
self.checker_command,
703
return True # Try again later
714
self.checker_command, exc_info=error)
715
return True # Try again later
704
716
self.current_checker_command = command
706
logger.info("Starting checker %r for %s", command,
718
logger.info("Starting checker %r for %s",
708
720
# We don't need to redirect stdout and stderr, since
709
721
# in normal mode, that is already done by daemon(),
710
722
# and in debug mode we don't want to. (Stdin is
719
731
"stderr": wnull })
720
732
self.checker = subprocess.Popen(command,
725
736
except OSError as error:
726
737
logger.error("Failed to start subprocess",
729
self.checker_callback_tag = gobject.child_watch_add(
730
self.checker.pid, self.checker_callback, data=command)
740
self.checker_callback_tag = (gobject.child_watch_add
742
self.checker_callback,
731
744
# The checker may have completed before the gobject
732
745
# watch was added. Check for this.
764
777
self.checker = None
767
def dbus_service_property(dbus_interface,
780
def dbus_service_property(dbus_interface, signature="v",
781
access="readwrite", byte_arrays=False):
771
782
"""Decorators for marking methods of a DBusObjectWithProperties to
772
783
become properties on the D-Bus.
782
793
# "Set" method, so we fail early here:
783
794
if byte_arrays and signature != "ay":
784
795
raise ValueError("Byte arrays not supported for non-'ay'"
785
" signature {!r}".format(signature))
796
" signature {0!r}".format(signature))
787
797
def decorator(func):
788
798
func._dbus_is_property = True
789
799
func._dbus_interface = dbus_interface
823
830
"""Decorator to annotate D-Bus methods, signals or properties
826
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
827
"org.freedesktop.DBus.Property."
828
"EmitsChangedSignal": "false"})
829
833
@dbus_service_property("org.example.Interface", signature="b",
835
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
836
"org.freedesktop.DBus.Property."
837
"EmitsChangedSignal": "false"})
831
838
def Property_dbus_property(self):
832
839
return dbus.Boolean(False)
835
841
def decorator(func):
836
842
func._dbus_annotations = annotations
842
847
class DBusPropertyException(dbus.exceptions.DBusException):
843
848
"""A base class for D-Bus property-related exceptions
850
def __unicode__(self):
851
return unicode(str(self))
848
854
class DBusPropertyAccessException(DBusPropertyException):
872
878
If called like _is_dbus_thing("method") it returns a function
873
879
suitable for use as predicate to inspect.getmembers().
875
return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
881
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
878
884
def _get_all_dbus_things(self, thing):
879
885
"""Returns a generator of (name, attribute) pairs
881
return ((getattr(athing.__get__(self), "_dbus_name", name),
887
return ((getattr(athing.__get__(self), "_dbus_name",
882
889
athing.__get__(self))
883
890
for cls in self.__class__.__mro__
884
891
for name, athing in
885
inspect.getmembers(cls, self._is_dbus_thing(thing)))
892
inspect.getmembers(cls,
893
self._is_dbus_thing(thing)))
887
895
def _get_dbus_property(self, interface_name, property_name):
888
896
"""Returns a bound method if one exists which is a D-Bus
889
897
property with the specified name and interface.
891
for cls in self.__class__.__mro__:
892
for name, value in inspect.getmembers(
893
cls, self._is_dbus_thing("property")):
899
for cls in self.__class__.__mro__:
900
for name, value in (inspect.getmembers
902
self._is_dbus_thing("property"))):
894
903
if (value._dbus_name == property_name
895
904
and value._dbus_interface == interface_name):
896
905
return value.__get__(self)
898
907
# No such property
899
raise DBusPropertyNotFound("{}:{}.{}".format(
900
self.dbus_object_path, interface_name, property_name))
908
raise DBusPropertyNotFound(self.dbus_object_path + ":"
909
+ interface_name + "."
902
@dbus.service.method(dbus.PROPERTIES_IFACE,
912
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
913
out_signature="v")
905
914
def Get(self, interface_name, property_name):
906
915
"""Standard D-Bus property Get() method, see D-Bus standard.
924
933
# The byte_arrays option is not supported yet on
925
934
# signatures other than "ay".
926
935
if prop._dbus_signature != "ay":
927
raise ValueError("Byte arrays not supported for non-"
928
"'ay' signature {!r}"
929
.format(prop._dbus_signature))
930
937
value = dbus.ByteArray(b''.join(chr(byte)
931
938
for byte in value))
934
@dbus.service.method(dbus.PROPERTIES_IFACE,
941
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
936
942
out_signature="a{sv}")
937
943
def GetAll(self, interface_name):
938
944
"""Standard D-Bus property GetAll() method, see D-Bus
953
959
if not hasattr(value, "variant_level"):
954
960
properties[name] = value
956
properties[name] = type(value)(
957
value, variant_level = value.variant_level + 1)
962
properties[name] = type(value)(value, variant_level=
963
value.variant_level+1)
958
964
return dbus.Dictionary(properties, signature="sv")
960
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
961
def PropertiesChanged(self, interface_name, changed_properties,
962
invalidated_properties):
963
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
968
966
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
969
967
out_signature="s",
970
968
path_keyword='object_path',
980
978
document = xml.dom.minidom.parseString(xmlstring)
982
979
def make_tag(document, name, prop):
983
980
e = document.createElement("property")
984
981
e.setAttribute("name", name)
985
982
e.setAttribute("type", prop._dbus_signature)
986
983
e.setAttribute("access", prop._dbus_access)
989
985
for if_tag in document.getElementsByTagName("interface"):
990
986
# Add property tags
991
987
for tag in (make_tag(document, name, prop)
1003
999
if (name == tag.getAttribute("name")
1004
1000
and prop._dbus_interface
1005
1001
== if_tag.getAttribute("name")):
1006
annots.update(getattr(
1007
prop, "_dbus_annotations", {}))
1008
for name, value in annots.items():
1002
annots.update(getattr
1004
"_dbus_annotations",
1006
for name, value in annots.iteritems():
1009
1007
ann_tag = document.createElement(
1011
1009
ann_tag.setAttribute("name", name)
1014
1012
# Add interface annotation tags
1015
1013
for annotation, value in dict(
1016
1014
itertools.chain.from_iterable(
1017
annotations().items()
1018
for name, annotations
1019
in self._get_all_dbus_things("interface")
1015
annotations().iteritems()
1016
for name, annotations in
1017
self._get_all_dbus_things("interface")
1020
1018
if name == if_tag.getAttribute("name")
1022
1020
ann_tag = document.createElement("annotation")
1023
1021
ann_tag.setAttribute("name", annotation)
1024
1022
ann_tag.setAttribute("value", value)
1051
1049
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1053
1051
return dbus.String("", variant_level = variant_level)
1054
return dbus.String(dt.isoformat(), variant_level=variant_level)
1052
return dbus.String(dt.isoformat(),
1053
variant_level=variant_level)
1057
1056
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1088
1086
# Ignore non-D-Bus attributes, and D-Bus attributes
1089
1087
# with the wrong interface name
1090
1088
if (not hasattr(attribute, "_dbus_interface")
1091
or not attribute._dbus_interface.startswith(
1092
orig_interface_name)):
1089
or not attribute._dbus_interface
1090
.startswith(orig_interface_name)):
1094
1092
# Create an alternate D-Bus interface name based on
1095
1093
# the current name
1096
alt_interface = attribute._dbus_interface.replace(
1097
orig_interface_name, alt_interface_name)
1094
alt_interface = (attribute._dbus_interface
1095
.replace(orig_interface_name,
1096
alt_interface_name))
1098
1097
interface_names.add(alt_interface)
1099
1098
# Is this a D-Bus signal?
1100
1099
if getattr(attribute, "_dbus_is_signal", False):
1101
1100
# Extract the original non-method undecorated
1102
1101
# function by black magic
1103
1102
nonmethod_func = (dict(
1104
zip(attribute.func_code.co_freevars,
1105
attribute.__closure__))
1106
["func"].cell_contents)
1103
zip(attribute.func_code.co_freevars,
1104
attribute.__closure__))["func"]
1107
1106
# Create a new, but exactly alike, function
1108
1107
# object, and decorate it to be a new D-Bus signal
1109
1108
# with the alternate D-Bus interface name
1110
new_function = (dbus.service.signal(
1111
alt_interface, attribute._dbus_signature)
1109
new_function = (dbus.service.signal
1111
attribute._dbus_signature)
1112
1112
(types.FunctionType(
1113
nonmethod_func.func_code,
1114
nonmethod_func.func_globals,
1115
nonmethod_func.func_name,
1116
nonmethod_func.func_defaults,
1117
nonmethod_func.func_closure)))
1113
nonmethod_func.func_code,
1114
nonmethod_func.func_globals,
1115
nonmethod_func.func_name,
1116
nonmethod_func.func_defaults,
1117
nonmethod_func.func_closure)))
1118
1118
# Copy annotations, if any
1120
new_function._dbus_annotations = dict(
1121
attribute._dbus_annotations)
1120
new_function._dbus_annotations = (
1121
dict(attribute._dbus_annotations))
1122
1122
except AttributeError:
1124
1124
# Define a creator of a function to call both the
1129
1129
"""This function is a scope container to pass
1130
1130
func1 and func2 to the "call_both" function
1131
1131
outside of its arguments"""
1133
1132
def call_both(*args, **kwargs):
1134
1133
"""This function will emit two D-Bus
1135
1134
signals by calling func1 and func2"""
1136
1135
func1(*args, **kwargs)
1137
1136
func2(*args, **kwargs)
1139
1137
return call_both
1140
1138
# Create the "call_both" function and add it to
1146
1144
# object. Decorate it to be a new D-Bus method
1147
1145
# with the alternate D-Bus interface name. Add it
1148
1146
# to the class.
1150
dbus.service.method(
1152
attribute._dbus_in_signature,
1153
attribute._dbus_out_signature)
1154
(types.FunctionType(attribute.func_code,
1155
attribute.func_globals,
1156
attribute.func_name,
1157
attribute.func_defaults,
1158
attribute.func_closure)))
1147
attr[attrname] = (dbus.service.method
1149
attribute._dbus_in_signature,
1150
attribute._dbus_out_signature)
1152
(attribute.func_code,
1153
attribute.func_globals,
1154
attribute.func_name,
1155
attribute.func_defaults,
1156
attribute.func_closure)))
1159
1157
# Copy annotations, if any
1161
attr[attrname]._dbus_annotations = dict(
1162
attribute._dbus_annotations)
1159
attr[attrname]._dbus_annotations = (
1160
dict(attribute._dbus_annotations))
1163
1161
except AttributeError:
1165
1163
# Is this a D-Bus property?
1168
1166
# object, and decorate it to be a new D-Bus
1169
1167
# property with the alternate D-Bus interface
1170
1168
# name. Add it to the class.
1171
attr[attrname] = (dbus_service_property(
1172
alt_interface, attribute._dbus_signature,
1173
attribute._dbus_access,
1174
attribute._dbus_get_args_options
1176
(types.FunctionType(
1177
attribute.func_code,
1178
attribute.func_globals,
1179
attribute.func_name,
1180
attribute.func_defaults,
1181
attribute.func_closure)))
1169
attr[attrname] = (dbus_service_property
1171
attribute._dbus_signature,
1172
attribute._dbus_access,
1174
._dbus_get_args_options
1177
(attribute.func_code,
1178
attribute.func_globals,
1179
attribute.func_name,
1180
attribute.func_defaults,
1181
attribute.func_closure)))
1182
1182
# Copy annotations, if any
1184
attr[attrname]._dbus_annotations = dict(
1185
attribute._dbus_annotations)
1184
attr[attrname]._dbus_annotations = (
1185
dict(attribute._dbus_annotations))
1186
1186
except AttributeError:
1188
1188
# Is this a D-Bus interface?
1191
1191
# object. Decorate it to be a new D-Bus interface
1192
1192
# with the alternate D-Bus interface name. Add it
1193
1193
# to the class.
1195
dbus_interface_annotations(alt_interface)
1196
(types.FunctionType(attribute.func_code,
1197
attribute.func_globals,
1198
attribute.func_name,
1199
attribute.func_defaults,
1200
attribute.func_closure)))
1194
attr[attrname] = (dbus_interface_annotations
1197
(attribute.func_code,
1198
attribute.func_globals,
1199
attribute.func_name,
1200
attribute.func_defaults,
1201
attribute.func_closure)))
1202
1203
# Deprecate all alternate interfaces
1203
iname="_AlternateDBusNames_interface_annotation{}"
1204
iname="_AlternateDBusNames_interface_annotation{0}"
1204
1205
for interface_name in interface_names:
1206
1206
@dbus_interface_annotations(interface_name)
1207
1207
def func(self):
1208
1208
return { "org.freedesktop.DBus.Deprecated":
1210
1210
# Find an unused name
1211
1211
for aname in (iname.format(i)
1212
1212
for i in itertools.count()):
1216
1216
if interface_names:
1217
1217
# Replace the class with a new subclass of it with
1218
1218
# methods, signals, etc. as created above.
1219
cls = type(b"{}Alternate".format(cls.__name__),
1219
cls = type(b"{0}Alternate".format(cls.__name__),
1226
1225
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
"se.bsnet.fukt.Mandos"})
1226
"se.bsnet.fukt.Mandos"})
1228
1227
class ClientDBus(Client, DBusObjectWithProperties):
1229
1228
"""A Client class using D-Bus
1245
1242
Client.__init__(self, *args, **kwargs)
1246
1243
# Only now, when this client is initialized, can it show up on
1248
client_object_name = str(self.name).translate(
1245
client_object_name = unicode(self.name).translate(
1249
1246
{ord("."): ord("_"),
1250
1247
ord("-"): ord("_")})
1251
self.dbus_object_path = dbus.ObjectPath(
1252
"/clients/" + client_object_name)
1248
self.dbus_object_path = (dbus.ObjectPath
1249
("/clients/" + client_object_name))
1253
1250
DBusObjectWithProperties.__init__(self, self.bus,
1254
1251
self.dbus_object_path)
1256
def notifychangeproperty(transform_func, dbus_name,
1257
type_func=lambda x: x,
1259
invalidate_only=False,
1260
_interface=_interface):
1253
def notifychangeproperty(transform_func,
1254
dbus_name, type_func=lambda x: x,
1261
1256
""" Modify a variable so that it's a property which announces
1262
1257
its changes to DBus.
1268
1263
to the D-Bus. Default: no transform
1269
1264
variant_level: D-Bus variant level. Default: 1
1271
attrname = "_{}".format(dbus_name)
1266
attrname = "_{0}".format(dbus_name)
1273
1267
def setter(self, value):
1274
1268
if hasattr(self, "dbus_object_path"):
1275
1269
if (not hasattr(self, attrname) or
1276
1270
type_func(getattr(self, attrname, None))
1277
1271
!= type_func(value)):
1279
self.PropertiesChanged(
1280
_interface, dbus.Dictionary(),
1281
dbus.Array((dbus_name, )))
1283
dbus_value = transform_func(
1285
variant_level = variant_level)
1286
self.PropertyChanged(dbus.String(dbus_name),
1288
self.PropertiesChanged(
1290
dbus.Dictionary({ dbus.String(dbus_name):
1272
dbus_value = transform_func(type_func(value),
1275
self.PropertyChanged(dbus.String(dbus_name),
1293
1277
setattr(self, attrname, value)
1295
1279
return property(lambda self: getattr(self, attrname), setter)
1301
1285
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1286
last_enabled = notifychangeproperty(datetime_to_dbus,
1304
checker = notifychangeproperty(
1305
dbus.Boolean, "CheckerRunning",
1306
type_func = lambda checker: checker is not None)
1288
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1289
type_func = lambda checker:
1290
checker is not None)
1307
1291
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1292
"LastCheckedOK")
1309
1293
last_checker_status = notifychangeproperty(dbus.Int16,
1312
1296
datetime_to_dbus, "LastApprovalRequest")
1313
1297
approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1298
"ApprovedByDefault")
1315
approval_delay = notifychangeproperty(
1316
dbus.UInt64, "ApprovalDelay",
1317
type_func = lambda td: td.total_seconds() * 1000)
1299
approval_delay = notifychangeproperty(dbus.UInt64,
1302
timedelta_to_milliseconds)
1318
1303
approval_duration = notifychangeproperty(
1319
1304
dbus.UInt64, "ApprovalDuration",
1320
type_func = lambda td: td.total_seconds() * 1000)
1305
type_func = timedelta_to_milliseconds)
1321
1306
host = notifychangeproperty(dbus.String, "Host")
1322
timeout = notifychangeproperty(
1323
dbus.UInt64, "Timeout",
1324
type_func = lambda td: td.total_seconds() * 1000)
1307
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1309
timedelta_to_milliseconds)
1325
1310
extended_timeout = notifychangeproperty(
1326
1311
dbus.UInt64, "ExtendedTimeout",
1327
type_func = lambda td: td.total_seconds() * 1000)
1328
interval = notifychangeproperty(
1329
dbus.UInt64, "Interval",
1330
type_func = lambda td: td.total_seconds() * 1000)
1312
type_func = timedelta_to_milliseconds)
1313
interval = notifychangeproperty(dbus.UInt64,
1316
timedelta_to_milliseconds)
1331
1317
checker_command = notifychangeproperty(dbus.String, "Checker")
1332
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
invalidate_only=True)
1335
1319
del notifychangeproperty
1363
1347
*args, **kwargs)
1365
1349
def start_checker(self, *args, **kwargs):
1366
old_checker_pid = getattr(self.checker, "pid", None)
1350
old_checker = self.checker
1351
if self.checker is not None:
1352
old_checker_pid = self.checker.pid
1354
old_checker_pid = None
1367
1355
r = Client.start_checker(self, *args, **kwargs)
1368
1356
# Only if new checker process was started
1369
1357
if (self.checker is not None
1379
1367
def approve(self, value=True):
1380
1368
self.approved = value
1381
gobject.timeout_add(int(self.approval_duration.total_seconds()
1382
* 1000), self._reset_approved)
1369
gobject.timeout_add(timedelta_to_milliseconds
1370
(self.approval_duration),
1371
self._reset_approved)
1383
1372
self.send_changedstate()
1385
1374
## D-Bus methods, signals & properties
1375
_interface = "se.recompile.Mandos.Client"
1379
@dbus_interface_annotations(_interface)
1381
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1391
1386
# CheckerCompleted - signal
1471
1465
return dbus.Boolean(bool(self.approvals_pending))
1473
1467
# ApprovedByDefault - property
1474
@dbus_service_property(_interface,
1468
@dbus_service_property(_interface, signature="b",
1476
1469
access="readwrite")
1477
1470
def ApprovedByDefault_dbus_property(self, value=None):
1478
1471
if value is None: # get
1480
1473
self.approved_by_default = bool(value)
1482
1475
# ApprovalDelay - property
1483
@dbus_service_property(_interface,
1476
@dbus_service_property(_interface, signature="t",
1485
1477
access="readwrite")
1486
1478
def ApprovalDelay_dbus_property(self, value=None):
1487
1479
if value is None: # get
1488
return dbus.UInt64(self.approval_delay.total_seconds()
1480
return dbus.UInt64(self.approval_delay_milliseconds())
1490
1481
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1492
1483
# ApprovalDuration - property
1493
@dbus_service_property(_interface,
1484
@dbus_service_property(_interface, signature="t",
1495
1485
access="readwrite")
1496
1486
def ApprovalDuration_dbus_property(self, value=None):
1497
1487
if value is None: # get
1498
return dbus.UInt64(self.approval_duration.total_seconds()
1488
return dbus.UInt64(timedelta_to_milliseconds(
1489
self.approval_duration))
1500
1490
self.approval_duration = datetime.timedelta(0, 0, 0, value)
1502
1492
# Name - property
1510
1500
return dbus.String(self.fingerprint)
1512
1502
# Host - property
1513
@dbus_service_property(_interface,
1503
@dbus_service_property(_interface, signature="s",
1515
1504
access="readwrite")
1516
1505
def Host_dbus_property(self, value=None):
1517
1506
if value is None: # get
1518
1507
return dbus.String(self.host)
1519
self.host = str(value)
1508
self.host = unicode(value)
1521
1510
# Created - property
1522
1511
@dbus_service_property(_interface, signature="s", access="read")
1551
1538
return datetime_to_dbus(self.last_checked_ok)
1553
1540
# LastCheckerStatus - property
1554
@dbus_service_property(_interface, signature="n", access="read")
1541
@dbus_service_property(_interface, signature="n",
1555
1543
def LastCheckerStatus_dbus_property(self):
1556
1544
return dbus.Int16(self.last_checker_status)
1566
1554
return datetime_to_dbus(self.last_approval_request)
1568
1556
# Timeout - property
1569
@dbus_service_property(_interface,
1557
@dbus_service_property(_interface, signature="t",
1571
1558
access="readwrite")
1572
1559
def Timeout_dbus_property(self, value=None):
1573
1560
if value is None: # get
1574
return dbus.UInt64(self.timeout.total_seconds() * 1000)
1561
return dbus.UInt64(self.timeout_milliseconds())
1575
1562
old_timeout = self.timeout
1576
1563
self.timeout = datetime.timedelta(0, 0, 0, value)
1577
1564
# Reschedule disabling
1588
1575
gobject.source_remove(self.disable_initiator_tag)
1589
self.disable_initiator_tag = gobject.timeout_add(
1590
int((self.expires - now).total_seconds() * 1000),
1576
self.disable_initiator_tag = (
1577
gobject.timeout_add(
1578
timedelta_to_milliseconds(self.expires - now),
1593
1581
# ExtendedTimeout - property
1594
@dbus_service_property(_interface,
1582
@dbus_service_property(_interface, signature="t",
1596
1583
access="readwrite")
1597
1584
def ExtendedTimeout_dbus_property(self, value=None):
1598
1585
if value is None: # get
1599
return dbus.UInt64(self.extended_timeout.total_seconds()
1586
return dbus.UInt64(self.extended_timeout_milliseconds())
1601
1587
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1603
1589
# Interval - property
1604
@dbus_service_property(_interface,
1590
@dbus_service_property(_interface, signature="t",
1606
1591
access="readwrite")
1607
1592
def Interval_dbus_property(self, value=None):
1608
1593
if value is None: # get
1609
return dbus.UInt64(self.interval.total_seconds() * 1000)
1594
return dbus.UInt64(self.interval_milliseconds())
1610
1595
self.interval = datetime.timedelta(0, 0, 0, value)
1611
1596
if getattr(self, "checker_initiator_tag", None) is None:
1613
1598
if self.enabled:
1614
1599
# Reschedule checker run
1615
1600
gobject.source_remove(self.checker_initiator_tag)
1616
self.checker_initiator_tag = gobject.timeout_add(
1617
value, self.start_checker)
1618
self.start_checker() # Start one now, too
1601
self.checker_initiator_tag = (gobject.timeout_add
1602
(value, self.start_checker))
1603
self.start_checker() # Start one now, too
1620
1605
# Checker - property
1621
@dbus_service_property(_interface,
1606
@dbus_service_property(_interface, signature="s",
1623
1607
access="readwrite")
1624
1608
def Checker_dbus_property(self, value=None):
1625
1609
if value is None: # get
1626
1610
return dbus.String(self.checker_command)
1627
self.checker_command = str(value)
1611
self.checker_command = unicode(value)
1629
1613
# CheckerRunning - property
1630
@dbus_service_property(_interface,
1614
@dbus_service_property(_interface, signature="b",
1632
1615
access="readwrite")
1633
1616
def CheckerRunning_dbus_property(self, value=None):
1634
1617
if value is None: # get
1644
1627
return self.dbus_object_path # is already a dbus.ObjectPath
1646
1629
# Secret = property
1647
@dbus_service_property(_interface,
1630
@dbus_service_property(_interface, signature="ay",
1631
access="write", byte_arrays=True)
1651
1632
def Secret_dbus_property(self, value):
1652
self.secret = bytes(value)
1633
self.secret = str(value)
1669
1650
if data[0] == 'data':
1671
1652
if data[0] == 'function':
1673
1653
def func(*args, **kwargs):
1674
1654
self._pipe.send(('funcall', name, args, kwargs))
1675
1655
return self._pipe.recv()[1]
1679
1658
def __setattr__(self, name, value):
1691
1670
def handle(self):
1692
1671
with contextlib.closing(self.server.child_pipe) as child_pipe:
1693
1672
logger.info("TCP connection from: %s",
1694
str(self.client_address))
1673
unicode(self.client_address))
1695
1674
logger.debug("Pipe FD: %d",
1696
1675
self.server.child_pipe.fileno())
1698
session = gnutls.connection.ClientSession(
1699
self.request, gnutls.connection .X509Credentials())
1677
session = (gnutls.connection
1678
.ClientSession(self.request,
1680
.X509Credentials()))
1701
1682
# Note: gnutls.connection.X509Credentials is really a
1702
1683
# generic GnuTLS certificate credentials object so long as
1711
1692
priority = self.server.gnutls_priority
1712
1693
if priority is None:
1713
1694
priority = "NORMAL"
1714
gnutls.library.functions.gnutls_priority_set_direct(
1715
session._c_object, priority, None)
1695
(gnutls.library.functions
1696
.gnutls_priority_set_direct(session._c_object,
1717
1699
# Start communication using the Mandos protocol
1718
1700
# Get protocol number
1788
1770
#wait until timeout or approved
1789
1771
time = datetime.datetime.now()
1790
1772
client.changedstate.acquire()
1791
client.changedstate.wait(delay.total_seconds())
1773
client.changedstate.wait(
1774
float(timedelta_to_milliseconds(delay)
1792
1776
client.changedstate.release()
1793
1777
time2 = datetime.datetime.now()
1794
1778
if (time2 - time) >= delay:
1813
1797
logger.warning("gnutls send failed",
1814
1798
exc_info=error)
1816
logger.debug("Sent: %d, remaining: %d", sent,
1817
len(client.secret) - (sent_size
1800
logger.debug("Sent: %d, remaining: %d",
1801
sent, len(client.secret)
1802
- (sent_size + sent))
1819
1803
sent_size += sent
1821
1805
logger.info("Sending secret to %s", client.name)
1838
1822
def peer_certificate(session):
1839
1823
"Return the peer's OpenPGP certificate as a bytestring"
1840
1824
# If not an OpenPGP certificate...
1841
if (gnutls.library.functions.gnutls_certificate_type_get(
1825
if (gnutls.library.functions
1826
.gnutls_certificate_type_get(session._c_object)
1843
1827
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1828
# ...do the normal thing
1845
1829
return session.peer_certificate
1859
1843
def fingerprint(openpgp):
1860
1844
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1845
# New GnuTLS "datum" with the OpenPGP public key
1862
datum = gnutls.library.types.gnutls_datum_t(
1863
ctypes.cast(ctypes.c_char_p(openpgp),
1864
ctypes.POINTER(ctypes.c_ubyte)),
1865
ctypes.c_uint(len(openpgp)))
1846
datum = (gnutls.library.types
1847
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1850
ctypes.c_uint(len(openpgp))))
1866
1851
# New empty GnuTLS certificate
1867
1852
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
gnutls.library.functions.gnutls_openpgp_crt_init(
1853
(gnutls.library.functions
1854
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1855
# Import the OpenPGP public key into the certificate
1871
gnutls.library.functions.gnutls_openpgp_crt_import(
1872
crt, ctypes.byref(datum),
1873
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
1856
(gnutls.library.functions
1857
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1858
gnutls.library.constants
1859
.GNUTLS_OPENPGP_FMT_RAW))
1874
1860
# Verify the self signature in the key
1875
1861
crtverify = ctypes.c_uint()
1876
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
crt, 0, ctypes.byref(crtverify))
1862
(gnutls.library.functions
1863
.gnutls_openpgp_crt_verify_self(crt, 0,
1864
ctypes.byref(crtverify)))
1878
1865
if crtverify.value != 0:
1879
1866
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
raise gnutls.errors.CertificateSecurityError(
1867
raise (gnutls.errors.CertificateSecurityError
1882
1869
# New buffer for the fingerprint
1883
1870
buf = ctypes.create_string_buffer(20)
1884
1871
buf_len = ctypes.c_size_t()
1885
1872
# Get the fingerprint from the certificate into the buffer
1886
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
crt, ctypes.byref(buf), ctypes.byref(buf_len))
1873
(gnutls.library.functions
1874
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1875
ctypes.byref(buf_len)))
1888
1876
# Deinit the certificate
1889
1877
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1878
# Convert the buffer to a Python bytestring
1941
1927
interface: None or a network interface name (string)
1942
1928
use_ipv6: Boolean; to use IPv6 or not
1945
1930
def __init__(self, server_address, RequestHandlerClass,
1931
interface=None, use_ipv6=True, socketfd=None):
1949
1932
"""If socketfd is set, use that file descriptor instead of
1950
1933
creating a new one with socket.socket().
1992
1975
self.interface)
1995
self.socket.setsockopt(
1996
socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
(self.interface + "\0").encode("utf-8"))
1978
self.socket.setsockopt(socket.SOL_SOCKET,
1980
str(self.interface + '\0'))
1998
1981
except socket.error as error:
1999
1982
if error.errno == errno.EPERM:
2000
1983
logger.error("No permission to bind to"
2018
2001
self.server_address = (any_address,
2019
2002
self.server_address[1])
2020
2003
elif not self.server_address[1]:
2021
self.server_address = (self.server_address[0], 0)
2004
self.server_address = (self.server_address[0],
2022
2006
# if self.interface:
2023
2007
# self.server_address = (self.server_address[0],
2039
2023
Assumes a gobject.MainLoop event loop.
2042
2025
def __init__(self, server_address, RequestHandlerClass,
2046
gnutls_priority=None,
2026
interface=None, use_ipv6=True, clients=None,
2027
gnutls_priority=None, use_dbus=True, socketfd=None):
2049
2028
self.enabled = False
2050
2029
self.clients = clients
2051
2030
if self.clients is None:
2068
2046
def add_pipe(self, parent_pipe, proc):
2069
2047
# Call "handle_ipc" for both data and EOF events
2070
gobject.io_add_watch(
2071
parent_pipe.fileno(),
2072
gobject.IO_IN | gobject.IO_HUP,
2073
functools.partial(self.handle_ipc,
2074
parent_pipe = parent_pipe,
2048
gobject.io_add_watch(parent_pipe.fileno(),
2049
gobject.IO_IN | gobject.IO_HUP,
2050
functools.partial(self.handle_ipc,
2077
def handle_ipc(self, source, condition,
2080
client_object=None):
2055
def handle_ipc(self, source, condition, parent_pipe=None,
2056
proc = None, client_object=None):
2081
2057
# error, or the other end of multiprocessing.Pipe has closed
2082
2058
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2059
# Wait for other process to exit
2106
2082
parent_pipe.send(False)
2109
gobject.io_add_watch(
2110
parent_pipe.fileno(),
2111
gobject.IO_IN | gobject.IO_HUP,
2112
functools.partial(self.handle_ipc,
2113
parent_pipe = parent_pipe,
2115
client_object = client))
2085
gobject.io_add_watch(parent_pipe.fileno(),
2086
gobject.IO_IN | gobject.IO_HUP,
2087
functools.partial(self.handle_ipc,
2116
2093
parent_pipe.send(True)
2117
2094
# remove the old hook in favor of the new above hook on
2125
2102
parent_pipe.send(('data', getattr(client_object,
2126
2103
funcname)(*args,
2129
2106
if command == 'getattr':
2130
2107
attrname = request[1]
2131
2108
if callable(client_object.__getattribute__(attrname)):
2132
parent_pipe.send(('function', ))
2109
parent_pipe.send(('function',))
2135
'data', client_object.__getattribute__(attrname)))
2111
parent_pipe.send(('data', client_object
2112
.__getattribute__(attrname)))
2137
2114
if command == 'setattr':
2138
2115
attrname = request[1]
2179
2156
"followers")) # Tokens valid after
2181
Token = collections.namedtuple("Token", (
2182
"regexp", # To match token; if "value" is not None, must have
2183
# a "group" containing digits
2184
"value", # datetime.timedelta or None
2185
"followers")) # Tokens valid after this token
2186
2158
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
2159
# the "duration" ABNF definition in RFC 3339, Appendix A.
2188
2160
token_end = Token(re.compile(r"$"), None, frozenset())
2189
2161
token_second = Token(re.compile(r"(\d+)S"),
2190
2162
datetime.timedelta(seconds=1),
2191
frozenset((token_end, )))
2163
frozenset((token_end,)))
2192
2164
token_minute = Token(re.compile(r"(\d+)M"),
2193
2165
datetime.timedelta(minutes=1),
2194
2166
frozenset((token_second, token_end)))
2210
2182
frozenset((token_month, token_end)))
2211
2183
token_week = Token(re.compile(r"(\d+)W"),
2212
2184
datetime.timedelta(weeks=1),
2213
frozenset((token_end, )))
2185
frozenset((token_end,)))
2214
2186
token_duration = Token(re.compile(r"P"), None,
2215
2187
frozenset((token_year, token_month,
2216
2188
token_day, token_time,
2218
2190
# Define starting values
2219
2191
value = datetime.timedelta() # Value so far
2220
2192
found_token = None
2221
followers = frozenset((token_duration,)) # Following valid tokens
2193
followers = frozenset(token_duration,) # Following valid tokens
2222
2194
s = duration # String left to parse
2223
2195
# Loop until end token is found
2224
2196
while found_token is not token_end:
2284
2256
elif suffix == "w":
2285
2257
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2287
raise ValueError("Unknown suffix {!r}".format(suffix))
2288
except IndexError as e:
2259
raise ValueError("Unknown suffix {0!r}"
2261
except (ValueError, IndexError) as e:
2289
2262
raise ValueError(*(e.args))
2290
2263
timevalue += delta
2291
2264
return timevalue
2307
2280
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2281
if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
2282
raise OSError(errno.ENODEV,
2310
"{} not a character device"
2283
"{0} not a character device"
2311
2284
.format(os.devnull))
2312
2285
os.dup2(null, sys.stdin.fileno())
2313
2286
os.dup2(null, sys.stdout.fileno())
2324
2297
parser = argparse.ArgumentParser()
2325
2298
parser.add_argument("-v", "--version", action="version",
2326
version = "%(prog)s {}".format(version),
2299
version = "%(prog)s {0}".format(version),
2327
2300
help="show version number and exit")
2328
2301
parser.add_argument("-i", "--interface", metavar="IF",
2329
2302
help="Bind to interface IF")
2362
2335
help="Directory to save/restore state in")
2363
2336
parser.add_argument("--foreground", action="store_true",
2364
2337
help="Run in foreground", default=None)
2365
parser.add_argument("--no-zeroconf", action="store_false",
2366
dest="zeroconf", help="Do not use Zeroconf",
2369
2339
options = parser.parse_args()
2371
2341
if options.check:
2373
fail_count, test_count = doctest.testmod()
2374
sys.exit(os.EX_OK if fail_count == 0 else 1)
2376
2346
# Default values for config file for server-global settings
2377
2347
server_defaults = { "interface": "",
2390
2359
"statedir": "/var/lib/mandos",
2391
2360
"foreground": "False",
2395
2363
# Parse config file for server-global settings
2396
2364
server_config = configparser.SafeConfigParser(server_defaults)
2397
2365
del server_defaults
2398
server_config.read(os.path.join(options.configdir, "mandos.conf"))
2366
server_config.read(os.path.join(options.configdir,
2399
2368
# Convert the SafeConfigParser object to a dict
2400
2369
server_settings = server_config.defaults()
2401
2370
# Use the appropriate methods on the non-string config options
2419
2388
# Override the settings from the config file with command line
2420
2389
# options, if set.
2421
2390
for option in ("interface", "address", "port", "debug",
2422
"priority", "servicename", "configdir", "use_dbus",
2423
"use_ipv6", "debuglevel", "restore", "statedir",
2424
"socket", "foreground", "zeroconf"):
2391
"priority", "servicename", "configdir",
2392
"use_dbus", "use_ipv6", "debuglevel", "restore",
2393
"statedir", "socket", "foreground"):
2425
2394
value = getattr(options, option)
2426
2395
if value is not None:
2427
2396
server_settings[option] = value
2429
2398
# Force all strings to be unicode
2430
2399
for option in server_settings.keys():
2431
if isinstance(server_settings[option], bytes):
2432
server_settings[option] = (server_settings[option]
2400
if type(server_settings[option]) is str:
2401
server_settings[option] = unicode(server_settings[option])
2434
2402
# Force all boolean options to be boolean
2435
2403
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2436
"foreground", "zeroconf"):
2437
2405
server_settings[option] = bool(server_settings[option])
2438
2406
# Debug implies foreground
2439
2407
if server_settings["debug"]:
2443
2411
##################################################################
2445
if (not server_settings["zeroconf"]
2446
and not (server_settings["port"]
2447
or server_settings["socket"] != "")):
2448
parser.error("Needs port or socket to work without Zeroconf")
2450
2413
# For convenience
2451
2414
debug = server_settings["debug"]
2452
2415
debuglevel = server_settings["debuglevel"]
2467
2429
initlogger(debug, level)
2469
2431
if server_settings["servicename"] != "Mandos":
2470
syslogger.setFormatter(
2471
logging.Formatter('Mandos ({}) [%(process)d]:'
2472
' %(levelname)s: %(message)s'.format(
2473
server_settings["servicename"])))
2432
syslogger.setFormatter(logging.Formatter
2433
('Mandos ({0}) [%(process)d]:'
2434
' %(levelname)s: %(message)s'
2435
.format(server_settings
2475
2438
# Parse config file with clients
2476
2439
client_config = configparser.SafeConfigParser(Client
2481
2444
global mandos_dbus_service
2482
2445
mandos_dbus_service = None
2485
if server_settings["socket"] != "":
2486
socketfd = server_settings["socket"]
2487
tcp_server = MandosServer(
2488
(server_settings["address"], server_settings["port"]),
2490
interface=(server_settings["interface"] or None),
2492
gnutls_priority=server_settings["priority"],
2447
tcp_server = MandosServer((server_settings["address"],
2448
server_settings["port"]),
2450
interface=(server_settings["interface"]
2454
server_settings["priority"],
2456
socketfd=(server_settings["socket"]
2495
2458
if not foreground:
2496
2459
pidfilename = "/run/mandos.pid"
2497
2460
if not os.path.isdir("/run/."):
2531
2494
def debug_gnutls(level, string):
2532
2495
logger.debug("GnuTLS: %s", string[:-1])
2534
gnutls.library.functions.gnutls_global_set_log_function(
2497
(gnutls.library.functions
2498
.gnutls_global_set_log_function(debug_gnutls))
2537
2500
# Redirect stdin so all checkers get /dev/null
2538
2501
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2560
2523
bus_name = dbus.service.BusName("se.recompile.Mandos",
2563
old_bus_name = dbus.service.BusName(
2564
"se.bsnet.fukt.Mandos", bus,
2524
bus, do_not_queue=True)
2525
old_bus_name = (dbus.service.BusName
2526
("se.bsnet.fukt.Mandos", bus,
2566
2528
except dbus.exceptions.NameExistsException as e:
2567
2529
logger.error("Disabling D-Bus:", exc_info=e)
2568
2530
use_dbus = False
2569
2531
server_settings["use_dbus"] = False
2570
2532
tcp_server.use_dbus = False
2572
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2573
service = AvahiServiceToSyslog(
2574
name = server_settings["servicename"],
2575
servicetype = "_mandos._tcp",
2576
protocol = protocol,
2578
if server_settings["interface"]:
2579
service.interface = if_nametoindex(
2580
server_settings["interface"].encode("utf-8"))
2533
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2534
service = AvahiServiceToSyslog(name =
2535
server_settings["servicename"],
2536
servicetype = "_mandos._tcp",
2537
protocol = protocol, bus = bus)
2538
if server_settings["interface"]:
2539
service.interface = (if_nametoindex
2540
(str(server_settings["interface"])))
2582
2542
global multiprocessing_manager
2583
2543
multiprocessing_manager = multiprocessing.Manager()
2602
2562
if server_settings["restore"]:
2604
2564
with open(stored_state_path, "rb") as stored_state:
2605
clients_data, old_client_settings = pickle.load(
2565
clients_data, old_client_settings = (pickle.load
2607
2567
os.remove(stored_state_path)
2608
2568
except IOError as e:
2609
2569
if e.errno == errno.ENOENT:
2610
logger.warning("Could not load persistent state:"
2611
" {}".format(os.strerror(e.errno)))
2570
logger.warning("Could not load persistent state: {0}"
2571
.format(os.strerror(e.errno)))
2613
2573
logger.critical("Could not load persistent state:",
2616
2576
except EOFError as e:
2617
2577
logger.warning("Could not load persistent state: "
2578
"EOFError:", exc_info=e)
2621
2580
with PGPEngine() as pgp:
2622
for client_name, client in clients_data.items():
2581
for client_name, client in clients_data.iteritems():
2623
2582
# Skip removed clients
2624
2583
if client_name not in client_settings:
2650
2609
if datetime.datetime.utcnow() >= client["expires"]:
2651
2610
if not client["last_checked_ok"]:
2652
2611
logger.warning(
2653
"disabling client {} - Client never "
2654
"performed a successful checker".format(
2612
"disabling client {0} - Client never "
2613
"performed a successful checker"
2614
.format(client_name))
2656
2615
client["enabled"] = False
2657
2616
elif client["last_checker_status"] != 0:
2658
2617
logger.warning(
2659
"disabling client {} - Client last"
2660
" checker failed with error code"
2663
client["last_checker_status"]))
2618
"disabling client {0} - Client "
2619
"last checker failed with error code {1}"
2620
.format(client_name,
2621
client["last_checker_status"]))
2664
2622
client["enabled"] = False
2666
client["expires"] = (
2667
datetime.datetime.utcnow()
2668
+ client["timeout"])
2624
client["expires"] = (datetime.datetime
2626
+ client["timeout"])
2669
2627
logger.debug("Last checker succeeded,"
2670
" keeping {} enabled".format(
2628
" keeping {0} enabled"
2629
.format(client_name))
2673
client["secret"] = pgp.decrypt(
2674
client["encrypted_secret"],
2675
client_settings[client_name]["secret"])
2631
client["secret"] = (
2632
pgp.decrypt(client["encrypted_secret"],
2633
client_settings[client_name]
2676
2635
except PGPError:
2677
2636
# If decryption fails, we use secret from new settings
2678
logger.debug("Failed to decrypt {} old secret".format(
2680
client["secret"] = (client_settings[client_name]
2637
logger.debug("Failed to decrypt {0} old secret"
2638
.format(client_name))
2639
client["secret"] = (
2640
client_settings[client_name]["secret"])
2683
2642
# Add/remove clients based on new changes made to config
2684
2643
for client_name in (set(old_client_settings)
2689
2648
clients_data[client_name] = client_settings[client_name]
2691
2650
# Create all client objects
2692
for client_name, client in clients_data.items():
2651
for client_name, client in clients_data.iteritems():
2693
2652
tcp_server.clients[client_name] = client_class(
2653
name = client_name, settings = client,
2696
2654
server_settings = server_settings)
2698
2656
if not tcp_server.clients:
2714
2672
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2718
@alternate_dbus_interfaces(
2719
{ "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2675
@alternate_dbus_interfaces({"se.recompile.Mandos":
2676
"se.bsnet.fukt.Mandos"})
2720
2677
class MandosDBusService(DBusObjectWithProperties):
2721
2678
"""A D-Bus proxy object"""
2723
2679
def __init__(self):
2724
2680
dbus.service.Object.__init__(self, bus, "/")
2726
2681
_interface = "se.recompile.Mandos"
2728
2683
@dbus_interface_annotations(_interface)
2729
2684
def _foo(self):
2731
"org.freedesktop.DBus.Property.EmitsChangedSignal":
2685
return { "org.freedesktop.DBus.Property"
2686
".EmitsChangedSignal":
2734
2689
@dbus.service.signal(_interface, signature="o")
2735
2690
def ClientAdded(self, objpath):
2757
2713
def GetAllClientsWithProperties(self):
2759
2715
return dbus.Dictionary(
2760
{ c.dbus_object_path: c.GetAll("")
2761
for c in tcp_server.clients.itervalues() },
2716
((c.dbus_object_path, c.GetAll(""))
2717
for c in tcp_server.clients.itervalues()),
2762
2718
signature="oa{sv}")
2764
2720
@dbus.service.method(_interface, in_signature="o")
2803
2758
# A list of attributes that can not be pickled
2805
exclude = { "bus", "changedstate", "secret",
2806
"checker", "server_settings" }
2807
for name, typ in inspect.getmembers(dbus.service
2760
exclude = set(("bus", "changedstate", "secret",
2761
"checker", "server_settings"))
2762
for name, typ in (inspect.getmembers
2763
(dbus.service.Object)):
2809
2764
exclude.add(name)
2811
2766
client_dict["encrypted_secret"] = (client
2818
2773
del client_settings[client.name]["secret"]
2821
with tempfile.NamedTemporaryFile(
2825
dir=os.path.dirname(stored_state_path),
2826
delete=False) as stored_state:
2776
with (tempfile.NamedTemporaryFile
2777
(mode='wb', suffix=".pickle", prefix='clients-',
2778
dir=os.path.dirname(stored_state_path),
2779
delete=False)) as stored_state:
2827
2780
pickle.dump((clients, client_settings), stored_state)
2828
tempname = stored_state.name
2781
tempname=stored_state.name
2829
2782
os.rename(tempname, stored_state_path)
2830
2783
except (IOError, OSError) as e:
2834
2787
except NameError:
2836
2789
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2837
logger.warning("Could not save persistent state: {}"
2790
logger.warning("Could not save persistent state: {0}"
2838
2791
.format(os.strerror(e.errno)))
2840
2793
logger.warning("Could not save persistent state:",
2844
2797
# Delete all clients, and settings from config
2845
2798
while tcp_server.clients:
2868
2822
tcp_server.server_activate()
2870
2824
# Find out what port we got
2872
service.port = tcp_server.socket.getsockname()[1]
2825
service.port = tcp_server.socket.getsockname()[1]
2874
2827
logger.info("Now listening on address %r, port %d,"
2875
2828
" flowinfo %d, scope_id %d",
2881
2834
#service.interface = tcp_server.socket.getsockname()[3]
2885
# From the Avahi example code
2888
except dbus.exceptions.DBusException as error:
2889
logger.critical("D-Bus Exception", exc_info=error)
2892
# End of Avahi example code
2837
# From the Avahi example code
2840
except dbus.exceptions.DBusException as error:
2841
logger.critical("D-Bus Exception", exc_info=error)
2844
# End of Avahi example code
2894
2846
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2895
2847
lambda *args, **kwargs: