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 + "."
649
611
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
650
612
out_signature="v")
742
704
xmlstring = document.toxml("utf-8")
743
705
document.unlink()
744
706
except (AttributeError, xml.dom.DOMException,
745
xml.parsers.expat.ExpatError) as error:
707
xml.parsers.expat.ExpatError), error:
746
708
logger.error("Failed to override Introspection method",
751
def datetime_to_dbus (dt, variant_level=0):
752
"""Convert a UTC datetime.datetime() to a D-Bus type."""
754
return dbus.String("", variant_level = variant_level)
755
return dbus.String(dt.isoformat(),
756
variant_level=variant_level)
758
class transitional_dbus_metaclass(DBusObjectWithProperties.__metaclass__):
759
def __new__(mcs, name, bases, attr):
760
for attrname, old_dbusobj in inspect.getmembers(bases[0]):
761
new_interface = getattr(old_dbusobj, "_dbus_interface", "").replace("se.bsnet.fukt.", "se.recompile.")
762
if (getattr(old_dbusobj, "_dbus_is_signal", False)
763
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
764
unwrappedfunc = dict(zip(old_dbusobj.func_code.co_freevars,
765
old_dbusobj.__closure__))["func"].cell_contents
766
newfunc = types.FunctionType(unwrappedfunc.func_code,
767
unwrappedfunc.func_globals,
768
unwrappedfunc.func_name,
769
unwrappedfunc.func_defaults,
770
unwrappedfunc.func_closure)
771
new_dbusfunc = dbus.service.signal(
772
new_interface, old_dbusobj._dbus_signature)(newfunc)
773
attr["_transitional_" + attrname] = new_dbusfunc
775
def fixscope(func1, func2):
776
def newcall(*args, **kwargs):
777
func1(*args, **kwargs)
778
func2(*args, **kwargs)
781
attr[attrname] = fixscope(old_dbusobj, new_dbusfunc)
783
elif (getattr(old_dbusobj, "_dbus_is_method", False)
784
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
785
new_dbusfunc = (dbus.service.method
787
old_dbusobj._dbus_in_signature,
788
old_dbusobj._dbus_out_signature)
790
(old_dbusobj.func_code,
791
old_dbusobj.func_globals,
792
old_dbusobj.func_name,
793
old_dbusobj.func_defaults,
794
old_dbusobj.func_closure)))
796
attr[attrname] = new_dbusfunc
797
elif (getattr(old_dbusobj, "_dbus_is_property", False)
798
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
799
new_dbusfunc = (dbus_service_property
801
old_dbusobj._dbus_signature,
802
old_dbusobj._dbus_access,
803
old_dbusobj._dbus_get_args_options["byte_arrays"])
805
(old_dbusobj.func_code,
806
old_dbusobj.func_globals,
807
old_dbusobj.func_name,
808
old_dbusobj.func_defaults,
809
old_dbusobj.func_closure)))
811
attr[attrname] = new_dbusfunc
812
return type.__new__(mcs, name, bases, attr)
814
713
class ClientDBus(Client, DBusObjectWithProperties):
815
714
"""A Client class using D-Bus
838
737
DBusObjectWithProperties.__init__(self, self.bus,
839
738
self.dbus_object_path)
841
def notifychangeproperty(transform_func,
842
dbus_name, type_func=lambda x: x,
844
""" Modify a variable so that its a property that announce its
846
transform_fun: Function that takes a value and transform it to
848
dbus_name: DBus name of the variable
849
type_func: Function that transform the value before sending it
851
variant_level: DBus variant level. default: 1
854
def setter(self, value):
855
old_value = real_value[0]
856
real_value[0] = value
857
if hasattr(self, "dbus_object_path"):
858
if type_func(old_value) != type_func(real_value[0]):
859
dbus_value = transform_func(type_func(real_value[0]),
861
self.PropertyChanged(dbus.String(dbus_name),
864
return property(lambda self: real_value[0], setter)
867
expires = notifychangeproperty(datetime_to_dbus, "Expires")
868
approvals_pending = notifychangeproperty(dbus.Boolean,
871
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
872
last_enabled = notifychangeproperty(datetime_to_dbus,
874
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
875
type_func = lambda checker: checker is not None)
876
last_checked_ok = notifychangeproperty(datetime_to_dbus,
878
last_approval_request = notifychangeproperty(datetime_to_dbus,
879
"LastApprovalRequest")
880
approved_by_default = notifychangeproperty(dbus.Boolean,
882
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
883
type_func = _timedelta_to_milliseconds)
884
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
885
type_func = _timedelta_to_milliseconds)
886
host = notifychangeproperty(dbus.String, "Host")
887
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
888
type_func = _timedelta_to_milliseconds)
889
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
890
type_func = _timedelta_to_milliseconds)
891
interval = notifychangeproperty(dbus.UInt16, "Interval",
892
type_func = _timedelta_to_milliseconds)
893
checker_command = notifychangeproperty(dbus.String, "Checker")
895
del notifychangeproperty
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"),
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))
897
784
def __del__(self, *args, **kwargs):
922
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,
925
833
def start_checker(self, *args, **kwargs):
926
834
old_checker = self.checker
927
835
if self.checker is not None:
934
842
and old_checker_pid != self.checker.pid):
935
843
# Emit D-Bus signal
936
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))
939
859
def _reset_approved(self):
940
860
self._approved = None
1049
972
if value is None: # get
1050
973
return dbus.UInt64(self.approval_delay_milliseconds())
1051
974
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
1053
979
# ApprovalDuration - property
1054
980
@dbus_service_property(_interface, signature="t",
1055
981
access="readwrite")
1056
982
def ApprovalDuration_dbus_property(self, value=None):
1057
983
if value is None: # get
1058
return dbus.UInt64(_timedelta_to_milliseconds(
984
return dbus.UInt64(self._timedelta_to_milliseconds(
1059
985
self.approval_duration))
1060
986
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
1062
991
# Name - property
1063
992
@dbus_service_property(_interface, signature="s", access="read")
1076
1005
if value is None: # get
1077
1006
return dbus.String(self.host)
1078
1007
self.host = value
1009
self.PropertyChanged(dbus.String("Host"),
1010
dbus.String(value, variant_level=1))
1080
1012
# Created - property
1081
1013
@dbus_service_property(_interface, signature="s", access="read")
1082
1014
def Created_dbus_property(self):
1083
return dbus.String(datetime_to_dbus(self.created))
1015
return dbus.String(self._datetime_to_dbus(self.created))
1085
1017
# LastEnabled - property
1086
1018
@dbus_service_property(_interface, signature="s", access="read")
1087
1019
def LastEnabled_dbus_property(self):
1088
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))
1090
1024
# Enabled - property
1091
1025
@dbus_service_property(_interface, signature="b",
1105
1039
if value is not None:
1106
1040
self.checked_ok()
1108
return datetime_to_dbus(self.last_checked_ok)
1110
# Expires - property
1111
@dbus_service_property(_interface, signature="s", access="read")
1112
def Expires_dbus_property(self):
1113
return datetime_to_dbus(self.expires)
1042
if self.last_checked_ok is None:
1043
return dbus.String("")
1044
return dbus.String(self._datetime_to_dbus(self
1115
1047
# LastApprovalRequest - property
1116
1048
@dbus_service_property(_interface, signature="s", access="read")
1117
1049
def LastApprovalRequest_dbus_property(self):
1118
return datetime_to_dbus(self.last_approval_request)
1050
if self.last_approval_request is None:
1051
return dbus.String("")
1052
return dbus.String(self.
1053
_datetime_to_dbus(self
1054
.last_approval_request))
1120
1056
# Timeout - property
1121
1057
@dbus_service_property(_interface, signature="t",
1140
1078
# The timeout has passed
1143
self.expires = (datetime.datetime.utcnow()
1144
+ datetime.timedelta(milliseconds = time_to_die))
1145
1081
self.disable_initiator_tag = (gobject.timeout_add
1146
1082
(time_to_die, self.disable))
1148
# ExtendedTimeout - property
1149
@dbus_service_property(_interface, signature="t",
1151
def ExtendedTimeout_dbus_property(self, value=None):
1152
if value is None: # get
1153
return dbus.UInt64(self.extended_timeout_milliseconds())
1154
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1156
1084
# Interval - property
1157
1085
@dbus_service_property(_interface, signature="t",
1158
1086
access="readwrite")
1241
1174
unicode(self.client_address))
1242
1175
logger.debug("Pipe FD: %d",
1243
1176
self.server.child_pipe.fileno())
1245
1178
session = (gnutls.connection
1246
1179
.ClientSession(self.request,
1247
1180
gnutls.connection
1248
1181
.X509Credentials()))
1250
1183
# Note: gnutls.connection.X509Credentials is really a
1251
1184
# generic GnuTLS certificate credentials object so long as
1252
1185
# no X.509 keys are added to it. Therefore, we can use it
1253
1186
# here despite using OpenPGP certificates.
1255
1188
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1256
1189
# "+AES-256-CBC", "+SHA1",
1257
1190
# "+COMP-NULL", "+CTYPE-OPENPGP",
1272
1205
if int(line.strip().split()[0]) > 1:
1273
1206
raise RuntimeError
1274
except (ValueError, IndexError, RuntimeError) as error:
1207
except (ValueError, IndexError, RuntimeError), error:
1275
1208
logger.error("Unknown protocol version: %s", error)
1278
1211
# Start GnuTLS connection
1280
1213
session.handshake()
1281
except gnutls.errors.GNUTLSError as error:
1214
except gnutls.errors.GNUTLSError, error:
1282
1215
logger.warning("Handshake failed: %s", error)
1283
1216
# Do not run session.bye() here: the session is not
1284
1217
# established. Just abandon the request.
1286
1219
logger.debug("Handshake succeeded")
1288
1221
approval_required = False
1291
1224
fpr = self.fingerprint(self.peer_certificate
1294
gnutls.errors.GNUTLSError) as error:
1226
except (TypeError, gnutls.errors.GNUTLSError), error:
1295
1227
logger.warning("Bad certificate: %s", error)
1297
1229
logger.debug("Fingerprint: %s", fpr)
1300
1232
client = ProxyClient(child_pipe, fpr,
1301
1233
self.client_address)
1743
1673
##################################################################
1744
1674
# Parsing of options, both command line and config file
1746
parser = argparse.ArgumentParser()
1747
parser.add_argument("-v", "--version", action="version",
1748
version = "%%(prog)s %s" % version,
1749
help="show version number and exit")
1750
parser.add_argument("-i", "--interface", metavar="IF",
1751
help="Bind to interface IF")
1752
parser.add_argument("-a", "--address",
1753
help="Address to listen for requests on")
1754
parser.add_argument("-p", "--port", type=int,
1755
help="Port number to receive requests on")
1756
parser.add_argument("--check", action="store_true",
1757
help="Run self-test")
1758
parser.add_argument("--debug", action="store_true",
1759
help="Debug mode; run in foreground and log"
1761
parser.add_argument("--debuglevel", metavar="LEVEL",
1762
help="Debug level for stdout output")
1763
parser.add_argument("--priority", help="GnuTLS"
1764
" priority string (see GnuTLS documentation)")
1765
parser.add_argument("--servicename",
1766
metavar="NAME", help="Zeroconf service name")
1767
parser.add_argument("--configdir",
1768
default="/etc/mandos", metavar="DIR",
1769
help="Directory to search for configuration"
1771
parser.add_argument("--no-dbus", action="store_false",
1772
dest="use_dbus", help="Do not provide D-Bus"
1773
" system bus interface")
1774
parser.add_argument("--no-ipv6", action="store_false",
1775
dest="use_ipv6", help="Do not use IPv6")
1776
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]
1778
1705
if options.check: