171
except dbus.exceptions.DBusException, error:
172
except dbus.exceptions.DBusException as error:
172
173
logger.critical("DBusException: %s", error)
175
176
self.rename_count += 1
176
177
def remove(self):
177
178
"""Derived from the Avahi example code"""
179
if self.entry_group_state_changed_match is not None:
180
self.entry_group_state_changed_match.remove()
181
self.entry_group_state_changed_match = None
178
182
if self.group is not None:
179
183
self.group.Reset()
181
185
"""Derived from the Avahi example code"""
182
187
if self.group is None:
183
188
self.group = dbus.Interface(
184
189
self.bus.get_object(avahi.DBUS_NAME,
185
190
self.server.EntryGroupNew()),
186
191
avahi.DBUS_INTERFACE_ENTRY_GROUP)
187
self.group.connect_to_signal('StateChanged',
189
.entry_group_state_changed)
192
self.entry_group_state_changed_match = (
193
self.group.connect_to_signal(
194
'StateChanged', self .entry_group_state_changed))
190
195
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
191
196
self.name, self.type)
192
197
self.group.AddService(
215
220
def cleanup(self):
216
221
"""Derived from the Avahi example code"""
217
222
if self.group is not None:
225
except (dbus.exceptions.UnknownMethodException,
226
dbus.exceptions.DBusException) as e:
219
228
self.group = None
220
def server_state_changed(self, state):
230
def server_state_changed(self, state, error=None):
221
231
"""Derived from the Avahi example code"""
222
232
logger.debug("Avahi server state change: %i", state)
223
if state == avahi.SERVER_COLLISION:
224
logger.error("Zeroconf server name collision")
233
bad_states = { avahi.SERVER_INVALID:
234
"Zeroconf server invalid",
235
avahi.SERVER_REGISTERING: None,
236
avahi.SERVER_COLLISION:
237
"Zeroconf server name collision",
238
avahi.SERVER_FAILURE:
239
"Zeroconf server failure" }
240
if state in bad_states:
241
if bad_states[state] is not None:
243
logger.error(bad_states[state])
245
logger.error(bad_states[state] + ": %r", error)
226
247
elif state == avahi.SERVER_RUNNING:
251
logger.debug("Unknown state: %r", state)
253
logger.debug("Unknown state: %r: %r", state, error)
228
254
def activate(self):
229
255
"""Derived from the Avahi example code"""
230
256
if self.server is None:
231
257
self.server = dbus.Interface(
232
258
self.bus.get_object(avahi.DBUS_NAME,
233
avahi.DBUS_PATH_SERVER),
259
avahi.DBUS_PATH_SERVER,
260
follow_name_owner_changes=True),
234
261
avahi.DBUS_INTERFACE_SERVER)
235
262
self.server.connect_to_signal("StateChanged",
236
263
self.server_state_changed)
237
264
self.server_state_changed(self.server.GetState())
267
def _timedelta_to_milliseconds(td):
268
"Convert a datetime.timedelta() to milliseconds"
269
return ((td.days * 24 * 60 * 60 * 1000)
270
+ (td.seconds * 1000)
271
+ (td.microseconds // 1000))
240
273
class Client(object):
241
274
"""A representation of a client host served by this server.
278
314
"host", "interval", "last_checked_ok",
279
315
"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
317
def timeout_milliseconds(self):
289
318
"Return the 'timeout' attribute in milliseconds"
290
return self._timedelta_to_milliseconds(self.timeout)
319
return _timedelta_to_milliseconds(self.timeout)
321
def extended_timeout_milliseconds(self):
322
"Return the 'extended_timeout' attribute in milliseconds"
323
return _timedelta_to_milliseconds(self.extended_timeout)
292
325
def interval_milliseconds(self):
293
326
"Return the 'interval' attribute in milliseconds"
294
return self._timedelta_to_milliseconds(self.interval)
327
return _timedelta_to_milliseconds(self.interval)
296
329
def approval_delay_milliseconds(self):
297
return self._timedelta_to_milliseconds(self.approval_delay)
330
return _timedelta_to_milliseconds(self.approval_delay)
299
332
def __init__(self, name = None, disable_hook=None, config=None):
300
333
"""Note: the 'checker' key in 'config' sets the
704
745
xmlstring = document.toxml("utf-8")
705
746
document.unlink()
706
747
except (AttributeError, xml.dom.DOMException,
707
xml.parsers.expat.ExpatError), error:
748
xml.parsers.expat.ExpatError) as error:
708
749
logger.error("Failed to override Introspection method",
754
def datetime_to_dbus (dt, variant_level=0):
755
"""Convert a UTC datetime.datetime() to a D-Bus type."""
757
return dbus.String("", variant_level = variant_level)
758
return dbus.String(dt.isoformat(),
759
variant_level=variant_level)
713
762
class ClientDBus(Client, DBusObjectWithProperties):
714
763
"""A Client class using D-Bus
737
786
DBusObjectWithProperties.__init__(self, self.bus,
738
787
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"),
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))
789
def notifychangeproperty(transform_func,
790
dbus_name, type_func=lambda x: x,
792
""" Modify a variable so that its a property that announce its
794
transform_fun: Function that takes a value and transform it to
796
dbus_name: DBus name of the variable
797
type_func: Function that transform the value before sending it
799
variant_level: DBus variant level. default: 1
802
def setter(self, value):
803
old_value = real_value[0]
804
real_value[0] = value
805
if hasattr(self, "dbus_object_path"):
806
if type_func(old_value) != type_func(real_value[0]):
807
dbus_value = transform_func(type_func(real_value[0]),
809
self.PropertyChanged(dbus.String(dbus_name),
812
return property(lambda self: real_value[0], setter)
815
expires = notifychangeproperty(datetime_to_dbus, "Expires")
816
approvals_pending = notifychangeproperty(dbus.Boolean,
819
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
820
last_enabled = notifychangeproperty(datetime_to_dbus,
822
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
823
type_func = lambda checker: checker is not None)
824
last_checked_ok = notifychangeproperty(datetime_to_dbus,
826
last_approval_request = notifychangeproperty(datetime_to_dbus,
827
"LastApprovalRequest")
828
approved_by_default = notifychangeproperty(dbus.Boolean,
830
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
831
type_func = _timedelta_to_milliseconds)
832
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
833
type_func = _timedelta_to_milliseconds)
834
host = notifychangeproperty(dbus.String, "Host")
835
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
836
type_func = _timedelta_to_milliseconds)
837
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
838
type_func = _timedelta_to_milliseconds)
839
interval = notifychangeproperty(dbus.UInt16, "Interval",
840
type_func = _timedelta_to_milliseconds)
841
checker_command = notifychangeproperty(dbus.String, "Checker")
843
del notifychangeproperty
784
845
def __del__(self, *args, **kwargs):
812
870
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
873
def start_checker(self, *args, **kwargs):
834
874
old_checker = self.checker
835
875
if self.checker is not None:
842
882
and old_checker_pid != self.checker.pid):
843
883
# Emit D-Bus signal
844
884
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
887
def _reset_approved(self):
860
888
self._approved = None
972
997
if value is None: # get
973
998
return dbus.UInt64(self.approval_delay_milliseconds())
974
999
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
979
1001
# ApprovalDuration - property
980
1002
@dbus_service_property(_interface, signature="t",
981
1003
access="readwrite")
982
1004
def ApprovalDuration_dbus_property(self, value=None):
983
1005
if value is None: # get
984
return dbus.UInt64(self._timedelta_to_milliseconds(
1006
return dbus.UInt64(_timedelta_to_milliseconds(
985
1007
self.approval_duration))
986
1008
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
991
1010
# Name - property
992
1011
@dbus_service_property(_interface, signature="s", access="read")
1005
1024
if value is None: # get
1006
1025
return dbus.String(self.host)
1007
1026
self.host = value
1009
self.PropertyChanged(dbus.String("Host"),
1010
dbus.String(value, variant_level=1))
1012
1028
# Created - property
1013
1029
@dbus_service_property(_interface, signature="s", access="read")
1014
1030
def Created_dbus_property(self):
1015
return dbus.String(self._datetime_to_dbus(self.created))
1031
return dbus.String(datetime_to_dbus(self.created))
1017
1033
# LastEnabled - property
1018
1034
@dbus_service_property(_interface, signature="s", access="read")
1019
1035
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))
1036
return datetime_to_dbus(self.last_enabled)
1024
1038
# Enabled - property
1025
1039
@dbus_service_property(_interface, signature="b",
1039
1053
if value is not None:
1040
1054
self.checked_ok()
1042
if self.last_checked_ok is None:
1043
return dbus.String("")
1044
return dbus.String(self._datetime_to_dbus(self
1056
return datetime_to_dbus(self.last_checked_ok)
1058
# Expires - property
1059
@dbus_service_property(_interface, signature="s", access="read")
1060
def Expires_dbus_property(self):
1061
return datetime_to_dbus(self.expires)
1047
1063
# LastApprovalRequest - property
1048
1064
@dbus_service_property(_interface, signature="s", access="read")
1049
1065
def LastApprovalRequest_dbus_property(self):
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))
1066
return datetime_to_dbus(self.last_approval_request)
1056
1068
# Timeout - property
1057
1069
@dbus_service_property(_interface, signature="t",
1078
1088
# The timeout has passed
1091
self.expires = (datetime.datetime.utcnow()
1092
+ datetime.timedelta(milliseconds = time_to_die))
1081
1093
self.disable_initiator_tag = (gobject.timeout_add
1082
1094
(time_to_die, self.disable))
1096
# ExtendedTimeout - property
1097
@dbus_service_property(_interface, signature="t",
1099
def ExtendedTimeout_dbus_property(self, value=None):
1100
if value is None: # get
1101
return dbus.UInt64(self.extended_timeout_milliseconds())
1102
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1084
1104
# Interval - property
1085
1105
@dbus_service_property(_interface, signature="t",
1086
1106
access="readwrite")
1174
1187
unicode(self.client_address))
1175
1188
logger.debug("Pipe FD: %d",
1176
1189
self.server.child_pipe.fileno())
1178
1191
session = (gnutls.connection
1179
1192
.ClientSession(self.request,
1180
1193
gnutls.connection
1181
1194
.X509Credentials()))
1183
1196
# Note: gnutls.connection.X509Credentials is really a
1184
1197
# generic GnuTLS certificate credentials object so long as
1185
1198
# no X.509 keys are added to it. Therefore, we can use it
1186
1199
# here despite using OpenPGP certificates.
1188
1201
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
1202
# "+AES-256-CBC", "+SHA1",
1190
1203
# "+COMP-NULL", "+CTYPE-OPENPGP",
1205
1218
if int(line.strip().split()[0]) > 1:
1206
1219
raise RuntimeError
1207
except (ValueError, IndexError, RuntimeError), error:
1220
except (ValueError, IndexError, RuntimeError) as error:
1208
1221
logger.error("Unknown protocol version: %s", error)
1211
1224
# Start GnuTLS connection
1213
1226
session.handshake()
1214
except gnutls.errors.GNUTLSError, error:
1227
except gnutls.errors.GNUTLSError as error:
1215
1228
logger.warning("Handshake failed: %s", error)
1216
1229
# Do not run session.bye() here: the session is not
1217
1230
# established. Just abandon the request.
1219
1232
logger.debug("Handshake succeeded")
1221
1234
approval_required = False
1224
1237
fpr = self.fingerprint(self.peer_certificate
1226
except (TypeError, gnutls.errors.GNUTLSError), error:
1240
gnutls.errors.GNUTLSError) as error:
1227
1241
logger.warning("Bad certificate: %s", error)
1229
1243
logger.debug("Fingerprint: %s", fpr)
1232
1246
client = ProxyClient(child_pipe, fpr,
1233
1247
self.client_address)
1673
1689
##################################################################
1674
1690
# 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]
1692
parser = argparse.ArgumentParser()
1693
parser.add_argument("-v", "--version", action="version",
1694
version = "%%(prog)s %s" % version,
1695
help="show version number and exit")
1696
parser.add_argument("-i", "--interface", metavar="IF",
1697
help="Bind to interface IF")
1698
parser.add_argument("-a", "--address",
1699
help="Address to listen for requests on")
1700
parser.add_argument("-p", "--port", type=int,
1701
help="Port number to receive requests on")
1702
parser.add_argument("--check", action="store_true",
1703
help="Run self-test")
1704
parser.add_argument("--debug", action="store_true",
1705
help="Debug mode; run in foreground and log"
1707
parser.add_argument("--debuglevel", metavar="LEVEL",
1708
help="Debug level for stdout output")
1709
parser.add_argument("--priority", help="GnuTLS"
1710
" priority string (see GnuTLS documentation)")
1711
parser.add_argument("--servicename",
1712
metavar="NAME", help="Zeroconf service name")
1713
parser.add_argument("--configdir",
1714
default="/etc/mandos", metavar="DIR",
1715
help="Directory to search for configuration"
1717
parser.add_argument("--no-dbus", action="store_false",
1718
dest="use_dbus", help="Do not provide D-Bus"
1719
" system bus interface")
1720
parser.add_argument("--no-ipv6", action="store_false",
1721
dest="use_ipv6", help="Do not use IPv6")
1722
options = parser.parse_args()
1705
1724
if options.check: