171
except dbus.exceptions.DBusException, error:
173
except dbus.exceptions.DBusException as error:
172
174
logger.critical("DBusException: %s", error)
175
177
self.rename_count += 1
176
178
def remove(self):
177
179
"""Derived from the Avahi example code"""
180
if self.entry_group_state_changed_match is not None:
181
self.entry_group_state_changed_match.remove()
182
self.entry_group_state_changed_match = None
178
183
if self.group is not None:
179
184
self.group.Reset()
181
186
"""Derived from the Avahi example code"""
182
188
if self.group is None:
183
189
self.group = dbus.Interface(
184
190
self.bus.get_object(avahi.DBUS_NAME,
185
191
self.server.EntryGroupNew()),
186
192
avahi.DBUS_INTERFACE_ENTRY_GROUP)
187
self.group.connect_to_signal('StateChanged',
189
.entry_group_state_changed)
193
self.entry_group_state_changed_match = (
194
self.group.connect_to_signal(
195
'StateChanged', self .entry_group_state_changed))
190
196
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
191
197
self.name, self.type)
192
198
self.group.AddService(
215
221
def cleanup(self):
216
222
"""Derived from the Avahi example code"""
217
223
if self.group is not None:
226
except (dbus.exceptions.UnknownMethodException,
227
dbus.exceptions.DBusException) as e:
219
229
self.group = None
220
def server_state_changed(self, state):
231
def server_state_changed(self, state, error=None):
221
232
"""Derived from the Avahi example code"""
222
233
logger.debug("Avahi server state change: %i", state)
223
if state == avahi.SERVER_COLLISION:
224
logger.error("Zeroconf server name collision")
234
bad_states = { avahi.SERVER_INVALID:
235
"Zeroconf server invalid",
236
avahi.SERVER_REGISTERING: None,
237
avahi.SERVER_COLLISION:
238
"Zeroconf server name collision",
239
avahi.SERVER_FAILURE:
240
"Zeroconf server failure" }
241
if state in bad_states:
242
if bad_states[state] is not None:
244
logger.error(bad_states[state])
246
logger.error(bad_states[state] + ": %r", error)
226
248
elif state == avahi.SERVER_RUNNING:
252
logger.debug("Unknown state: %r", state)
254
logger.debug("Unknown state: %r: %r", state, error)
228
255
def activate(self):
229
256
"""Derived from the Avahi example code"""
230
257
if self.server is None:
231
258
self.server = dbus.Interface(
232
259
self.bus.get_object(avahi.DBUS_NAME,
233
avahi.DBUS_PATH_SERVER),
260
avahi.DBUS_PATH_SERVER,
261
follow_name_owner_changes=True),
234
262
avahi.DBUS_INTERFACE_SERVER)
235
263
self.server.connect_to_signal("StateChanged",
236
264
self.server_state_changed)
237
265
self.server_state_changed(self.server.GetState())
268
def _timedelta_to_milliseconds(td):
269
"Convert a datetime.timedelta() to milliseconds"
270
return ((td.days * 24 * 60 * 60 * 1000)
271
+ (td.seconds * 1000)
272
+ (td.microseconds // 1000))
240
274
class Client(object):
241
275
"""A representation of a client host served by this server.
278
315
"host", "interval", "last_checked_ok",
279
316
"last_enabled", "name", "timeout")
282
def _timedelta_to_milliseconds(td):
283
"Convert a datetime.timedelta() to milliseconds"
284
return ((td.days * 24 * 60 * 60 * 1000)
285
+ (td.seconds * 1000)
286
+ (td.microseconds // 1000))
288
318
def timeout_milliseconds(self):
289
319
"Return the 'timeout' attribute in milliseconds"
290
return self._timedelta_to_milliseconds(self.timeout)
320
return _timedelta_to_milliseconds(self.timeout)
322
def extended_timeout_milliseconds(self):
323
"Return the 'extended_timeout' attribute in milliseconds"
324
return _timedelta_to_milliseconds(self.extended_timeout)
292
326
def interval_milliseconds(self):
293
327
"Return the 'interval' attribute in milliseconds"
294
return self._timedelta_to_milliseconds(self.interval)
328
return _timedelta_to_milliseconds(self.interval)
296
330
def approval_delay_milliseconds(self):
297
return self._timedelta_to_milliseconds(self.approval_delay)
331
return _timedelta_to_milliseconds(self.approval_delay)
299
333
def __init__(self, name = None, disable_hook=None, config=None):
300
334
"""Note: the 'checker' key in 'config' sets the
585
627
def _get_all_dbus_properties(self):
586
628
"""Returns a generator of (name, attribute) pairs
588
return ((prop._dbus_name, prop)
590
inspect.getmembers(self, self._is_dbus_property))
630
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
631
for cls in self.__class__.__mro__
632
for name, prop in inspect.getmembers(cls, self._is_dbus_property))
592
634
def _get_dbus_property(self, interface_name, property_name):
593
635
"""Returns a bound method if one exists which is a D-Bus
594
636
property with the specified name and interface.
596
for name in (property_name,
597
property_name + "_dbus_property"):
598
prop = getattr(self, name, None)
600
or not self._is_dbus_property(prop)
601
or prop._dbus_name != property_name
602
or (interface_name and prop._dbus_interface
603
and interface_name != prop._dbus_interface)):
638
for cls in self.__class__.__mro__:
639
for name, value in inspect.getmembers(cls, self._is_dbus_property):
640
if value._dbus_name == property_name and value._dbus_interface == interface_name:
641
return value.__get__(self)
606
643
# No such property
607
644
raise DBusPropertyNotFound(self.dbus_object_path + ":"
608
645
+ interface_name + "."
704
741
xmlstring = document.toxml("utf-8")
705
742
document.unlink()
706
743
except (AttributeError, xml.dom.DOMException,
707
xml.parsers.expat.ExpatError), error:
744
xml.parsers.expat.ExpatError) as error:
708
745
logger.error("Failed to override Introspection method",
750
def datetime_to_dbus (dt, variant_level=0):
751
"""Convert a UTC datetime.datetime() to a D-Bus type."""
753
return dbus.String("", variant_level = variant_level)
754
return dbus.String(dt.isoformat(),
755
variant_level=variant_level)
757
class AlternateDBusNamesMetaclass(DBusObjectWithProperties.__metaclass__):
758
"""Applied to an empty subclass of a D-Bus object, this metaclass
759
will add additional D-Bus attributes matching a certain pattern.
761
def __new__(mcs, name, bases, attr):
762
# Go through all the base classes which could have D-Bus
763
# methods, signals, or properties in them
764
for base in (b for b in bases
765
if issubclass(b, dbus.service.Object)):
766
# Go though all attributes of the base class
767
for attrname, attribute in inspect.getmembers(base):
768
# Ignore non-D-Bus attributes, and D-Bus attributes
769
# with the wrong interface name
770
if (not hasattr(attribute, "_dbus_interface")
771
or not attribute._dbus_interface
772
.startswith("se.recompile.Mandos")):
774
# Create an alternate D-Bus interface name based on
776
alt_interface = (attribute._dbus_interface
777
.replace("se.recompile.Mandos",
778
"se.bsnet.fukt.Mandos"))
779
# Is this a D-Bus signal?
780
if getattr(attribute, "_dbus_is_signal", False):
781
# Extract the original non-method function by
783
nonmethod_func = (dict(
784
zip(attribute.func_code.co_freevars,
785
attribute.__closure__))["func"]
787
# Create a new, but exactly alike, function
788
# object, and decorate it to be a new D-Bus signal
789
# with the alternate D-Bus interface name
790
new_function = (dbus.service.signal
792
attribute._dbus_signature)
794
nonmethod_func.func_code,
795
nonmethod_func.func_globals,
796
nonmethod_func.func_name,
797
nonmethod_func.func_defaults,
798
nonmethod_func.func_closure)))
799
# Define a creator of a function to call both the
800
# old and new functions, so both the old and new
801
# signals gets sent when the function is called
802
def fixscope(func1, func2):
803
"""This function is a scope container to pass
804
func1 and func2 to the "call_both" function
805
outside of its arguments"""
806
def call_both(*args, **kwargs):
807
"""This function will emit two D-Bus
808
signals by calling func1 and func2"""
809
func1(*args, **kwargs)
810
func2(*args, **kwargs)
812
# Create the "call_both" function and add it to
814
attr[attrname] = fixscope(attribute,
816
# Is this a D-Bus method?
817
elif getattr(attribute, "_dbus_is_method", False):
818
# Create a new, but exactly alike, function
819
# object. Decorate it to be a new D-Bus method
820
# with the alternate D-Bus interface name. Add it
822
attr[attrname] = (dbus.service.method
824
attribute._dbus_in_signature,
825
attribute._dbus_out_signature)
827
(attribute.func_code,
828
attribute.func_globals,
830
attribute.func_defaults,
831
attribute.func_closure)))
832
# Is this a D-Bus property?
833
elif getattr(attribute, "_dbus_is_property", False):
834
# Create a new, but exactly alike, function
835
# object, and decorate it to be a new D-Bus
836
# property with the alternate D-Bus interface
837
# name. Add it to the class.
838
attr[attrname] = (dbus_service_property
840
attribute._dbus_signature,
841
attribute._dbus_access,
843
._dbus_get_args_options
846
(attribute.func_code,
847
attribute.func_globals,
849
attribute.func_defaults,
850
attribute.func_closure)))
851
return type.__new__(mcs, name, bases, attr)
713
853
class ClientDBus(Client, DBusObjectWithProperties):
714
854
"""A Client class using D-Bus
737
877
DBusObjectWithProperties.__init__(self, self.bus,
738
878
self.dbus_object_path)
740
def _get_approvals_pending(self):
741
return self._approvals_pending
742
def _set_approvals_pending(self, value):
743
old_value = self._approvals_pending
744
self._approvals_pending = value
746
if (hasattr(self, "dbus_object_path")
747
and bval is not bool(old_value)):
748
dbus_bool = dbus.Boolean(bval, variant_level=1)
749
self.PropertyChanged(dbus.String("ApprovalPending"),
880
def notifychangeproperty(transform_func,
881
dbus_name, type_func=lambda x: x,
883
""" Modify a variable so that it's a property which announces
752
approvals_pending = property(_get_approvals_pending,
753
_set_approvals_pending)
754
del _get_approvals_pending, _set_approvals_pending
757
def _datetime_to_dbus(dt, variant_level=0):
758
"""Convert a UTC datetime.datetime() to a D-Bus type."""
759
return dbus.String(dt.isoformat(),
760
variant_level=variant_level)
763
oldstate = getattr(self, "enabled", False)
764
r = Client.enable(self)
765
if oldstate != self.enabled:
767
self.PropertyChanged(dbus.String("Enabled"),
768
dbus.Boolean(True, variant_level=1))
769
self.PropertyChanged(
770
dbus.String("LastEnabled"),
771
self._datetime_to_dbus(self.last_enabled,
775
def disable(self, quiet = False):
776
oldstate = getattr(self, "enabled", False)
777
r = Client.disable(self, quiet=quiet)
778
if not quiet and oldstate != self.enabled:
780
self.PropertyChanged(dbus.String("Enabled"),
781
dbus.Boolean(False, variant_level=1))
886
transform_fun: Function that takes a value and transforms it
888
dbus_name: D-Bus name of the variable
889
type_func: Function that transform the value before sending it
890
to the D-Bus. Default: no transform
891
variant_level: D-Bus variant level. Default: 1
894
def setter(self, value):
895
old_value = real_value[0]
896
real_value[0] = value
897
if hasattr(self, "dbus_object_path"):
898
if type_func(old_value) != type_func(real_value[0]):
899
dbus_value = transform_func(type_func(real_value[0]),
901
self.PropertyChanged(dbus.String(dbus_name),
904
return property(lambda self: real_value[0], setter)
907
expires = notifychangeproperty(datetime_to_dbus, "Expires")
908
approvals_pending = notifychangeproperty(dbus.Boolean,
911
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
912
last_enabled = notifychangeproperty(datetime_to_dbus,
914
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
915
type_func = lambda checker: checker is not None)
916
last_checked_ok = notifychangeproperty(datetime_to_dbus,
918
last_approval_request = notifychangeproperty(datetime_to_dbus,
919
"LastApprovalRequest")
920
approved_by_default = notifychangeproperty(dbus.Boolean,
922
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
923
type_func = _timedelta_to_milliseconds)
924
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
925
type_func = _timedelta_to_milliseconds)
926
host = notifychangeproperty(dbus.String, "Host")
927
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
928
type_func = _timedelta_to_milliseconds)
929
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
930
type_func = _timedelta_to_milliseconds)
931
interval = notifychangeproperty(dbus.UInt16, "Interval",
932
type_func = _timedelta_to_milliseconds)
933
checker_command = notifychangeproperty(dbus.String, "Checker")
935
del notifychangeproperty
784
937
def __del__(self, *args, **kwargs):
812
962
return Client.checker_callback(self, pid, condition, command,
815
def checked_ok(self, *args, **kwargs):
816
r = Client.checked_ok(self, *args, **kwargs)
818
self.PropertyChanged(
819
dbus.String("LastCheckedOK"),
820
(self._datetime_to_dbus(self.last_checked_ok,
824
def need_approval(self, *args, **kwargs):
825
r = Client.need_approval(self, *args, **kwargs)
827
self.PropertyChanged(
828
dbus.String("LastApprovalRequest"),
829
(self._datetime_to_dbus(self.last_approval_request,
833
965
def start_checker(self, *args, **kwargs):
834
966
old_checker = self.checker
835
967
if self.checker is not None:
842
974
and old_checker_pid != self.checker.pid):
843
975
# Emit D-Bus signal
844
976
self.CheckerStarted(self.current_checker_command)
845
self.PropertyChanged(
846
dbus.String("CheckerRunning"),
847
dbus.Boolean(True, variant_level=1))
850
def stop_checker(self, *args, **kwargs):
851
old_checker = getattr(self, "checker", None)
852
r = Client.stop_checker(self, *args, **kwargs)
853
if (old_checker is not None
854
and getattr(self, "checker", None) is None):
855
self.PropertyChanged(dbus.String("CheckerRunning"),
856
dbus.Boolean(False, variant_level=1))
859
979
def _reset_approved(self):
860
980
self._approved = None
972
1089
if value is None: # get
973
1090
return dbus.UInt64(self.approval_delay_milliseconds())
974
1091
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
979
1093
# ApprovalDuration - property
980
1094
@dbus_service_property(_interface, signature="t",
981
1095
access="readwrite")
982
1096
def ApprovalDuration_dbus_property(self, value=None):
983
1097
if value is None: # get
984
return dbus.UInt64(self._timedelta_to_milliseconds(
1098
return dbus.UInt64(_timedelta_to_milliseconds(
985
1099
self.approval_duration))
986
1100
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
991
1102
# Name - property
992
1103
@dbus_service_property(_interface, signature="s", access="read")
1005
1116
if value is None: # get
1006
1117
return dbus.String(self.host)
1007
1118
self.host = value
1009
self.PropertyChanged(dbus.String("Host"),
1010
dbus.String(value, variant_level=1))
1012
1120
# Created - property
1013
1121
@dbus_service_property(_interface, signature="s", access="read")
1014
1122
def Created_dbus_property(self):
1015
return dbus.String(self._datetime_to_dbus(self.created))
1123
return dbus.String(datetime_to_dbus(self.created))
1017
1125
# LastEnabled - property
1018
1126
@dbus_service_property(_interface, signature="s", access="read")
1019
1127
def LastEnabled_dbus_property(self):
1020
if self.last_enabled is None:
1021
return dbus.String("")
1022
return dbus.String(self._datetime_to_dbus(self.last_enabled))
1128
return datetime_to_dbus(self.last_enabled)
1024
1130
# Enabled - property
1025
1131
@dbus_service_property(_interface, signature="b",
1205
1312
if int(line.strip().split()[0]) > 1:
1206
1313
raise RuntimeError
1207
except (ValueError, IndexError, RuntimeError), error:
1314
except (ValueError, IndexError, RuntimeError) as error:
1208
1315
logger.error("Unknown protocol version: %s", error)
1211
1318
# Start GnuTLS connection
1213
1320
session.handshake()
1214
except gnutls.errors.GNUTLSError, error:
1321
except gnutls.errors.GNUTLSError as error:
1215
1322
logger.warning("Handshake failed: %s", error)
1216
1323
# Do not run session.bye() here: the session is not
1217
1324
# established. Just abandon the request.
1219
1326
logger.debug("Handshake succeeded")
1221
1328
approval_required = False
1224
1331
fpr = self.fingerprint(self.peer_certificate
1226
except (TypeError, gnutls.errors.GNUTLSError), error:
1334
gnutls.errors.GNUTLSError) as error:
1227
1335
logger.warning("Bad certificate: %s", error)
1229
1337
logger.debug("Fingerprint: %s", fpr)
1232
1340
client = ProxyClient(child_pipe, fpr,
1233
1341
self.client_address)
1673
1783
##################################################################
1674
1784
# Parsing of options, both command line and config file
1676
parser = optparse.OptionParser(version = "%%prog %s" % version)
1677
parser.add_option("-i", "--interface", type="string",
1678
metavar="IF", help="Bind to interface IF")
1679
parser.add_option("-a", "--address", type="string",
1680
help="Address to listen for requests on")
1681
parser.add_option("-p", "--port", type="int",
1682
help="Port number to receive requests on")
1683
parser.add_option("--check", action="store_true",
1684
help="Run self-test")
1685
parser.add_option("--debug", action="store_true",
1686
help="Debug mode; run in foreground and log to"
1688
parser.add_option("--debuglevel", type="string", metavar="LEVEL",
1689
help="Debug level for stdout output")
1690
parser.add_option("--priority", type="string", help="GnuTLS"
1691
" priority string (see GnuTLS documentation)")
1692
parser.add_option("--servicename", type="string",
1693
metavar="NAME", help="Zeroconf service name")
1694
parser.add_option("--configdir", type="string",
1695
default="/etc/mandos", metavar="DIR",
1696
help="Directory to search for configuration"
1698
parser.add_option("--no-dbus", action="store_false",
1699
dest="use_dbus", help="Do not provide D-Bus"
1700
" system bus interface")
1701
parser.add_option("--no-ipv6", action="store_false",
1702
dest="use_ipv6", help="Do not use IPv6")
1703
options = parser.parse_args()[0]
1786
parser = argparse.ArgumentParser()
1787
parser.add_argument("-v", "--version", action="version",
1788
version = "%%(prog)s %s" % version,
1789
help="show version number and exit")
1790
parser.add_argument("-i", "--interface", metavar="IF",
1791
help="Bind to interface IF")
1792
parser.add_argument("-a", "--address",
1793
help="Address to listen for requests on")
1794
parser.add_argument("-p", "--port", type=int,
1795
help="Port number to receive requests on")
1796
parser.add_argument("--check", action="store_true",
1797
help="Run self-test")
1798
parser.add_argument("--debug", action="store_true",
1799
help="Debug mode; run in foreground and log"
1801
parser.add_argument("--debuglevel", metavar="LEVEL",
1802
help="Debug level for stdout output")
1803
parser.add_argument("--priority", help="GnuTLS"
1804
" priority string (see GnuTLS documentation)")
1805
parser.add_argument("--servicename",
1806
metavar="NAME", help="Zeroconf service name")
1807
parser.add_argument("--configdir",
1808
default="/etc/mandos", metavar="DIR",
1809
help="Directory to search for configuration"
1811
parser.add_argument("--no-dbus", action="store_false",
1812
dest="use_dbus", help="Do not provide D-Bus"
1813
" system bus interface")
1814
parser.add_argument("--no-ipv6", action="store_false",
1815
dest="use_ipv6", help="Do not use IPv6")
1816
options = parser.parse_args()
1705
1818
if options.check: