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
631
589
for name, prop in
632
590
inspect.getmembers(self, self._is_dbus_property))
634
# def _get_dbus_property(self, interface_name, property_name):
635
# """Returns a bound method if one exists which is a D-Bus
636
# property with the specified name and interface.
638
# print("get_property({0!r}, {1!r}".format(interface_name, property_name),file=sys.stderr)
639
# print(dir(self), sys.stderr)
640
# for name in (property_name,
641
# property_name + "_dbus_property"):
642
# prop = getattr(self, name, None)
644
# or not self._is_dbus_property(prop)
645
# or prop._dbus_name != property_name
646
# or (interface_name and prop._dbus_interface
647
# and interface_name != prop._dbus_interface)):
651
# raise DBusPropertyNotFound(self.dbus_object_path + ":"
652
# + interface_name + "."
655
592
def _get_dbus_property(self, interface_name, property_name):
656
593
"""Returns a bound method if one exists which is a D-Bus
657
594
property with the specified name and interface.
659
for name, value in inspect.getmembers(self, self._is_dbus_property):
660
if value._dbus_name == property_name and value._dbus_interface == interface_name:
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)):
663
606
# No such property
664
607
raise DBusPropertyNotFound(self.dbus_object_path + ":"
665
608
+ interface_name + "."
669
611
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
670
612
out_signature="v")
762
704
xmlstring = document.toxml("utf-8")
763
705
document.unlink()
764
706
except (AttributeError, xml.dom.DOMException,
765
xml.parsers.expat.ExpatError) as error:
707
xml.parsers.expat.ExpatError), error:
766
708
logger.error("Failed to override Introspection method",
771
def datetime_to_dbus (dt, variant_level=0):
772
"""Convert a UTC datetime.datetime() to a D-Bus type."""
774
return dbus.String("", variant_level = variant_level)
775
return dbus.String(dt.isoformat(),
776
variant_level=variant_level)
778
class transitional_clientdbus(DBusObjectWithProperties.__metaclass__):
779
def __new__(mcs, name, bases, attr):
780
for key, old_dbusobj in attr.items():
781
new_interface = getattr(old_dbusobj, "_dbus_interface", "").replace("se.bsnet.fukt.", "se.recompile.")
782
if getattr(old_dbusobj, "_dbus_is_signal", False):
783
unwrappedfunc = dict(zip(old_dbusobj.func_code.co_freevars,
784
old_dbusobj.__closure__))["func"].cell_contents
785
newfunc = types.FunctionType(unwrappedfunc.func_code,
786
unwrappedfunc.func_globals,
787
unwrappedfunc.func_name,
788
unwrappedfunc.func_defaults,
789
unwrappedfunc.func_closure)
790
new_dbusfunc = dbus.service.signal(
791
new_interface, old_dbusobj._dbus_signature)(newfunc)
792
attr["_transitional_{0}_1".format(key)] = new_dbusfunc
793
attr["_transitional_{0}_0".format(key)] = old_dbusobj
794
def fixscope(func1, func2):
795
def newcall(*args, **kwargs):
796
func1(*args, **kwargs)
797
func2(*args, **kwargs)
800
attr[key] = fixscope(
801
old_dbusobj, attr["_transitional_{0}_1".format(key)])
803
if getattr(old_dbusobj, "_dbus_is_method", False):
804
new_dbusfunc = (dbus.service.method
806
old_dbusobj._dbus_in_signature,
807
old_dbusobj._dbus_out_signature)
809
(old_dbusobj.func_code,
810
old_dbusobj.func_globals,
811
old_dbusobj.func_name,
812
old_dbusobj.func_defaults,
813
old_dbusobj.func_closure)))
815
attr["_transitional_{0}".format(key)] = new_dbusfunc
816
if getattr(old_dbusobj, "_dbus_is_property", False):
817
new_dbusfunc = (dbus_service_property
819
old_dbusobj._dbus_signature,
820
old_dbusobj._dbus_access,
821
old_dbusobj._dbus_get_args_options["byte_arrays"])
823
(old_dbusobj.func_code,
824
old_dbusobj.func_globals,
825
old_dbusobj.func_name,
826
old_dbusobj.func_defaults,
827
old_dbusobj.func_closure)))
829
attr["_transitional_{0}".format(key)] = new_dbusfunc
830
return type.__new__(mcs, name, bases, attr)
832
713
class ClientDBus(Client, DBusObjectWithProperties):
833
714
"""A Client class using D-Bus
858
737
DBusObjectWithProperties.__init__(self, self.bus,
859
738
self.dbus_object_path)
861
def notifychangeproperty(transform_func,
862
dbus_name, type_func=lambda x: x,
864
""" Modify a variable so that its a property that announce its
866
transform_fun: Function that takes a value and transform it to
868
dbus_name: DBus name of the variable
869
type_func: Function that transform the value before sending it
871
variant_level: DBus variant level. default: 1
874
def setter(self, value):
875
old_value = real_value[0]
876
real_value[0] = value
877
if hasattr(self, "dbus_object_path"):
878
if type_func(old_value) != type_func(real_value[0]):
879
dbus_value = transform_func(type_func(real_value[0]),
881
self.PropertyChanged(dbus.String(dbus_name),
884
return property(lambda self: real_value[0], setter)
887
expires = notifychangeproperty(datetime_to_dbus, "Expires")
888
approvals_pending = notifychangeproperty(dbus.Boolean,
891
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
892
last_enabled = notifychangeproperty(datetime_to_dbus,
894
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
895
type_func = lambda checker: checker is not None)
896
last_checked_ok = notifychangeproperty(datetime_to_dbus,
898
last_approval_request = notifychangeproperty(datetime_to_dbus,
899
"LastApprovalRequest")
900
approved_by_default = notifychangeproperty(dbus.Boolean,
902
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
903
type_func = _timedelta_to_milliseconds)
904
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
905
type_func = _timedelta_to_milliseconds)
906
host = notifychangeproperty(dbus.String, "Host")
907
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
908
type_func = _timedelta_to_milliseconds)
909
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
910
type_func = _timedelta_to_milliseconds)
911
interval = notifychangeproperty(dbus.UInt16, "Interval",
912
type_func = _timedelta_to_milliseconds)
913
checker_command = notifychangeproperty(dbus.String, "Checker")
915
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))
917
784
def __del__(self, *args, **kwargs):
942
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,
945
833
def start_checker(self, *args, **kwargs):
946
834
old_checker = self.checker
947
835
if self.checker is not None:
954
842
and old_checker_pid != self.checker.pid):
955
843
# Emit D-Bus signal
956
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))
959
859
def _reset_approved(self):
960
860
self._approved = None
1069
972
if value is None: # get
1070
973
return dbus.UInt64(self.approval_delay_milliseconds())
1071
974
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
1073
979
# ApprovalDuration - property
1074
980
@dbus_service_property(_interface, signature="t",
1075
981
access="readwrite")
1076
982
def ApprovalDuration_dbus_property(self, value=None):
1077
983
if value is None: # get
1078
return dbus.UInt64(_timedelta_to_milliseconds(
984
return dbus.UInt64(self._timedelta_to_milliseconds(
1079
985
self.approval_duration))
1080
986
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
1082
991
# Name - property
1083
992
@dbus_service_property(_interface, signature="s", access="read")
1096
1005
if value is None: # get
1097
1006
return dbus.String(self.host)
1098
1007
self.host = value
1009
self.PropertyChanged(dbus.String("Host"),
1010
dbus.String(value, variant_level=1))
1100
1012
# Created - property
1101
1013
@dbus_service_property(_interface, signature="s", access="read")
1102
1014
def Created_dbus_property(self):
1103
return dbus.String(datetime_to_dbus(self.created))
1015
return dbus.String(self._datetime_to_dbus(self.created))
1105
1017
# LastEnabled - property
1106
1018
@dbus_service_property(_interface, signature="s", access="read")
1107
1019
def LastEnabled_dbus_property(self):
1108
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))
1110
1024
# Enabled - property
1111
1025
@dbus_service_property(_interface, signature="b",
1125
1039
if value is not None:
1126
1040
self.checked_ok()
1128
return datetime_to_dbus(self.last_checked_ok)
1130
# Expires - property
1131
@dbus_service_property(_interface, signature="s", access="read")
1132
def Expires_dbus_property(self):
1133
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
1135
1047
# LastApprovalRequest - property
1136
1048
@dbus_service_property(_interface, signature="s", access="read")
1137
1049
def LastApprovalRequest_dbus_property(self):
1138
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))
1140
1056
# Timeout - property
1141
1057
@dbus_service_property(_interface, signature="t",
1160
1078
# The timeout has passed
1163
self.expires = (datetime.datetime.utcnow()
1164
+ datetime.timedelta(milliseconds = time_to_die))
1165
1081
self.disable_initiator_tag = (gobject.timeout_add
1166
1082
(time_to_die, self.disable))
1168
# ExtendedTimeout - property
1169
@dbus_service_property(_interface, signature="t",
1171
def ExtendedTimeout_dbus_property(self, value=None):
1172
if value is None: # get
1173
return dbus.UInt64(self.extended_timeout_milliseconds())
1174
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1176
1084
# Interval - property
1177
1085
@dbus_service_property(_interface, signature="t",
1178
1086
access="readwrite")
1259
1174
unicode(self.client_address))
1260
1175
logger.debug("Pipe FD: %d",
1261
1176
self.server.child_pipe.fileno())
1263
1178
session = (gnutls.connection
1264
1179
.ClientSession(self.request,
1265
1180
gnutls.connection
1266
1181
.X509Credentials()))
1268
1183
# Note: gnutls.connection.X509Credentials is really a
1269
1184
# generic GnuTLS certificate credentials object so long as
1270
1185
# no X.509 keys are added to it. Therefore, we can use it
1271
1186
# here despite using OpenPGP certificates.
1273
1188
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1274
1189
# "+AES-256-CBC", "+SHA1",
1275
1190
# "+COMP-NULL", "+CTYPE-OPENPGP",
1290
1205
if int(line.strip().split()[0]) > 1:
1291
1206
raise RuntimeError
1292
except (ValueError, IndexError, RuntimeError) as error:
1207
except (ValueError, IndexError, RuntimeError), error:
1293
1208
logger.error("Unknown protocol version: %s", error)
1296
1211
# Start GnuTLS connection
1298
1213
session.handshake()
1299
except gnutls.errors.GNUTLSError as error:
1214
except gnutls.errors.GNUTLSError, error:
1300
1215
logger.warning("Handshake failed: %s", error)
1301
1216
# Do not run session.bye() here: the session is not
1302
1217
# established. Just abandon the request.
1304
1219
logger.debug("Handshake succeeded")
1306
1221
approval_required = False
1309
1224
fpr = self.fingerprint(self.peer_certificate
1312
gnutls.errors.GNUTLSError) as error:
1226
except (TypeError, gnutls.errors.GNUTLSError), error:
1313
1227
logger.warning("Bad certificate: %s", error)
1315
1229
logger.debug("Fingerprint: %s", fpr)
1318
1232
client = ProxyClient(child_pipe, fpr,
1319
1233
self.client_address)
1761
1673
##################################################################
1762
1674
# Parsing of options, both command line and config file
1764
parser = argparse.ArgumentParser()
1765
parser.add_argument("-v", "--version", action="version",
1766
version = "%%(prog)s %s" % version,
1767
help="show version number and exit")
1768
parser.add_argument("-i", "--interface", metavar="IF",
1769
help="Bind to interface IF")
1770
parser.add_argument("-a", "--address",
1771
help="Address to listen for requests on")
1772
parser.add_argument("-p", "--port", type=int,
1773
help="Port number to receive requests on")
1774
parser.add_argument("--check", action="store_true",
1775
help="Run self-test")
1776
parser.add_argument("--debug", action="store_true",
1777
help="Debug mode; run in foreground and log"
1779
parser.add_argument("--debuglevel", metavar="LEVEL",
1780
help="Debug level for stdout output")
1781
parser.add_argument("--priority", help="GnuTLS"
1782
" priority string (see GnuTLS documentation)")
1783
parser.add_argument("--servicename",
1784
metavar="NAME", help="Zeroconf service name")
1785
parser.add_argument("--configdir",
1786
default="/etc/mandos", metavar="DIR",
1787
help="Directory to search for configuration"
1789
parser.add_argument("--no-dbus", action="store_false",
1790
dest="use_dbus", help="Do not provide D-Bus"
1791
" system bus interface")
1792
parser.add_argument("--no-ipv6", action="store_false",
1793
dest="use_ipv6", help="Do not use IPv6")
1794
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]
1796
1705
if options.check: