173
except dbus.exceptions.DBusException as error:
171
except dbus.exceptions.DBusException, error:
174
172
logger.critical("DBusException: %s", error)
177
175
self.rename_count += 1
178
176
def remove(self):
179
177
"""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
183
178
if self.group is not None:
184
179
self.group.Reset()
186
181
"""Derived from the Avahi example code"""
188
182
if self.group is None:
189
183
self.group = dbus.Interface(
190
184
self.bus.get_object(avahi.DBUS_NAME,
191
185
self.server.EntryGroupNew()),
192
186
avahi.DBUS_INTERFACE_ENTRY_GROUP)
193
self.entry_group_state_changed_match = (
194
self.group.connect_to_signal(
195
'StateChanged', self .entry_group_state_changed))
187
self.group.connect_to_signal('StateChanged',
189
.entry_group_state_changed)
196
190
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
197
191
self.name, self.type)
198
192
self.group.AddService(
221
215
def cleanup(self):
222
216
"""Derived from the Avahi example code"""
223
217
if self.group is not None:
226
except (dbus.exceptions.UnknownMethodException,
227
dbus.exceptions.DBusException) as e:
229
219
self.group = None
231
def server_state_changed(self, state, error=None):
220
def server_state_changed(self, state):
232
221
"""Derived from the Avahi example code"""
233
222
logger.debug("Avahi server state change: %i", state)
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)
223
if state == avahi.SERVER_COLLISION:
224
logger.error("Zeroconf server name collision")
248
226
elif state == avahi.SERVER_RUNNING:
252
logger.debug("Unknown state: %r", state)
254
logger.debug("Unknown state: %r: %r", state, error)
255
228
def activate(self):
256
229
"""Derived from the Avahi example code"""
257
230
if self.server is None:
258
231
self.server = dbus.Interface(
259
232
self.bus.get_object(avahi.DBUS_NAME,
260
avahi.DBUS_PATH_SERVER,
261
follow_name_owner_changes=True),
233
avahi.DBUS_PATH_SERVER),
262
234
avahi.DBUS_INTERFACE_SERVER)
263
235
self.server.connect_to_signal("StateChanged",
264
236
self.server_state_changed)
265
237
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))
274
240
class Client(object):
275
241
"""A representation of a client host served by this server.
315
278
"host", "interval", "last_checked_ok",
316
279
"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))
318
288
def timeout_milliseconds(self):
319
289
"Return the 'timeout' attribute in milliseconds"
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)
290
return self._timedelta_to_milliseconds(self.timeout)
326
292
def interval_milliseconds(self):
327
293
"Return the 'interval' attribute in milliseconds"
328
return _timedelta_to_milliseconds(self.interval)
294
return self._timedelta_to_milliseconds(self.interval)
330
296
def approval_delay_milliseconds(self):
331
return _timedelta_to_milliseconds(self.approval_delay)
297
return self._timedelta_to_milliseconds(self.approval_delay)
333
299
def __init__(self, name = None, disable_hook=None, config=None):
334
300
"""Note: the 'checker' key in 'config' sets the
627
585
def _get_all_dbus_properties(self):
628
586
"""Returns a generator of (name, attribute) pairs
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))
588
return ((prop._dbus_name, prop)
590
inspect.getmembers(self, self._is_dbus_property))
634
592
def _get_dbus_property(self, interface_name, property_name):
635
593
"""Returns a bound method if one exists which is a D-Bus
636
594
property with the specified name and 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)
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)):
643
606
# No such property
644
607
raise DBusPropertyNotFound(self.dbus_object_path + ":"
645
608
+ interface_name + "."
741
704
xmlstring = document.toxml("utf-8")
742
705
document.unlink()
743
706
except (AttributeError, xml.dom.DOMException,
744
xml.parsers.expat.ExpatError) as error:
707
xml.parsers.expat.ExpatError), error:
745
708
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)
853
713
class ClientDBus(Client, DBusObjectWithProperties):
854
714
"""A Client class using D-Bus
877
737
DBusObjectWithProperties.__init__(self, self.bus,
878
738
self.dbus_object_path)
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
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"),
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
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))
937
784
def __del__(self, *args, **kwargs):
962
812
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,
965
833
def start_checker(self, *args, **kwargs):
966
834
old_checker = self.checker
967
835
if self.checker is not None:
974
842
and old_checker_pid != self.checker.pid):
975
843
# Emit D-Bus signal
976
844
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))
979
859
def _reset_approved(self):
980
860
self._approved = None
1089
972
if value is None: # get
1090
973
return dbus.UInt64(self.approval_delay_milliseconds())
1091
974
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
1093
979
# ApprovalDuration - property
1094
980
@dbus_service_property(_interface, signature="t",
1095
981
access="readwrite")
1096
982
def ApprovalDuration_dbus_property(self, value=None):
1097
983
if value is None: # get
1098
return dbus.UInt64(_timedelta_to_milliseconds(
984
return dbus.UInt64(self._timedelta_to_milliseconds(
1099
985
self.approval_duration))
1100
986
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
1102
991
# Name - property
1103
992
@dbus_service_property(_interface, signature="s", access="read")
1116
1005
if value is None: # get
1117
1006
return dbus.String(self.host)
1118
1007
self.host = value
1009
self.PropertyChanged(dbus.String("Host"),
1010
dbus.String(value, variant_level=1))
1120
1012
# Created - property
1121
1013
@dbus_service_property(_interface, signature="s", access="read")
1122
1014
def Created_dbus_property(self):
1123
return dbus.String(datetime_to_dbus(self.created))
1015
return dbus.String(self._datetime_to_dbus(self.created))
1125
1017
# LastEnabled - property
1126
1018
@dbus_service_property(_interface, signature="s", access="read")
1127
1019
def LastEnabled_dbus_property(self):
1128
return datetime_to_dbus(self.last_enabled)
1020
if self.last_enabled is None:
1021
return dbus.String("")
1022
return dbus.String(self._datetime_to_dbus(self.last_enabled))
1130
1024
# Enabled - property
1131
1025
@dbus_service_property(_interface, signature="b",
1312
1205
if int(line.strip().split()[0]) > 1:
1313
1206
raise RuntimeError
1314
except (ValueError, IndexError, RuntimeError) as error:
1207
except (ValueError, IndexError, RuntimeError), error:
1315
1208
logger.error("Unknown protocol version: %s", error)
1318
1211
# Start GnuTLS connection
1320
1213
session.handshake()
1321
except gnutls.errors.GNUTLSError as error:
1214
except gnutls.errors.GNUTLSError, error:
1322
1215
logger.warning("Handshake failed: %s", error)
1323
1216
# Do not run session.bye() here: the session is not
1324
1217
# established. Just abandon the request.
1326
1219
logger.debug("Handshake succeeded")
1328
1221
approval_required = False
1331
1224
fpr = self.fingerprint(self.peer_certificate
1334
gnutls.errors.GNUTLSError) as error:
1226
except (TypeError, gnutls.errors.GNUTLSError), error:
1335
1227
logger.warning("Bad certificate: %s", error)
1337
1229
logger.debug("Fingerprint: %s", fpr)
1340
1232
client = ProxyClient(child_pipe, fpr,
1341
1233
self.client_address)
1783
1673
##################################################################
1784
1674
# Parsing of options, both command line and config file
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()
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]
1818
1705
if options.check: