152
154
def rename(self):
153
155
"""Derived from the Avahi example code"""
154
156
if self.rename_count >= self.max_renames:
155
logger.critical(u"No suitable Zeroconf service name found"
156
u" after %i retries, exiting.",
157
logger.critical("No suitable Zeroconf service name found"
158
" after %i retries, exiting.",
157
159
self.rename_count)
158
raise AvahiServiceError(u"Too many renames")
159
self.name = self.server.GetAlternativeServiceName(self.name)
160
logger.info(u"Changing Zeroconf service name to %r ...",
160
raise AvahiServiceError("Too many renames")
161
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
162
logger.info("Changing Zeroconf service name to %r ...",
162
164
syslogger.setFormatter(logging.Formatter
163
(u'Mandos (%s) [%%(process)d]:'
164
u' %%(levelname)s: %%(message)s'
165
('Mandos (%s) [%%(process)d]:'
166
' %%(levelname)s: %%(message)s'
171
except dbus.exceptions.DBusException, error:
172
logger.critical("DBusException: %s", error)
168
175
self.rename_count += 1
169
176
def remove(self):
170
177
"""Derived from the Avahi example code"""
193
200
self.group.Commit()
194
201
def entry_group_state_changed(self, state, error):
195
202
"""Derived from the Avahi example code"""
196
logger.debug(u"Avahi state change: %i", state)
203
logger.debug("Avahi entry group state change: %i", state)
198
205
if state == avahi.ENTRY_GROUP_ESTABLISHED:
199
logger.debug(u"Zeroconf service established.")
206
logger.debug("Zeroconf service established.")
200
207
elif state == avahi.ENTRY_GROUP_COLLISION:
201
logger.warning(u"Zeroconf service name collision.")
208
logger.info("Zeroconf service name collision.")
203
210
elif state == avahi.ENTRY_GROUP_FAILURE:
204
logger.critical(u"Avahi: Error in group state changed %s",
211
logger.critical("Avahi: Error in group state changed %s",
206
raise AvahiGroupError(u"State changed: %s"
213
raise AvahiGroupError("State changed: %s"
207
214
% unicode(error))
208
215
def cleanup(self):
209
216
"""Derived from the Avahi example code"""
233
241
"""A representation of a client host served by this server.
236
name: string; from the config file, used in log messages and
244
_approved: bool(); 'None' if not yet approved/disapproved
245
approval_delay: datetime.timedelta(); Time to wait for approval
246
approval_duration: datetime.timedelta(); Duration of one approval
247
checker: subprocess.Popen(); a running checker process used
248
to see if the client lives.
249
'None' if no process is running.
250
checker_callback_tag: a gobject event source tag, or None
251
checker_command: string; External command which is run to check
252
if client lives. %() expansions are done at
253
runtime with vars(self) as dict, so that for
254
instance %(name)s can be used in the command.
255
checker_initiator_tag: a gobject event source tag, or None
256
created: datetime.datetime(); (UTC) object creation
257
current_checker_command: string; current running checker_command
258
disable_hook: If set, called by disable() as disable_hook(self)
259
disable_initiator_tag: a gobject event source tag, or None
238
261
fingerprint: string (40 or 32 hexadecimal digits); used to
239
262
uniquely identify the client
240
secret: bytestring; sent verbatim (over TLS) to client
241
263
host: string; available for use by the checker command
242
created: datetime.datetime(); (UTC) object creation
264
interval: datetime.timedelta(); How often to start a new checker
265
last_approval_request: datetime.datetime(); (UTC) or None
266
last_checked_ok: datetime.datetime(); (UTC) or None
243
267
last_enabled: datetime.datetime(); (UTC)
245
last_checked_ok: datetime.datetime(); (UTC) or None
268
name: string; from the config file, used in log messages and
270
secret: bytestring; sent verbatim (over TLS) to client
246
271
timeout: datetime.timedelta(); How long from last_checked_ok
247
272
until this client is disabled
248
interval: datetime.timedelta(); How often to start a new checker
249
disable_hook: If set, called by disable() as disable_hook(self)
250
checker: subprocess.Popen(); a running checker process used
251
to see if the client lives.
252
'None' if no process is running.
253
checker_initiator_tag: a gobject event source tag, or None
254
disable_initiator_tag: - '' -
255
checker_callback_tag: - '' -
256
checker_command: string; External command which is run to check if
257
client lives. %() expansions are done at
258
runtime with vars(self) as dict, so that for
259
instance %(name)s can be used in the command.
260
current_checker_command: string; current running checker_command
261
approved_delay: datetime.timedelta(); Time to wait for approval
262
_approved: bool(); 'None' if not yet approved/disapproved
263
approved_duration: datetime.timedelta(); Duration of one approval
273
runtime_expansions: Allowed attributes for runtime expansion.
276
runtime_expansions = ("approval_delay", "approval_duration",
277
"created", "enabled", "fingerprint",
278
"host", "interval", "last_checked_ok",
279
"last_enabled", "name", "timeout")
267
282
def _timedelta_to_milliseconds(td):
268
283
"Convert a datetime.timedelta() to milliseconds"
289
304
if config is None:
291
logger.debug(u"Creating client %r", self.name)
306
logger.debug("Creating client %r", self.name)
292
307
# Uppercase and remove spaces from fingerprint for later
293
308
# comparison purposes with return value from the fingerprint()
295
self.fingerprint = (config[u"fingerprint"].upper()
297
logger.debug(u" Fingerprint: %s", self.fingerprint)
298
if u"secret" in config:
299
self.secret = config[u"secret"].decode(u"base64")
300
elif u"secfile" in config:
310
self.fingerprint = (config["fingerprint"].upper()
312
logger.debug(" Fingerprint: %s", self.fingerprint)
313
if "secret" in config:
314
self.secret = config["secret"].decode("base64")
315
elif "secfile" in config:
301
316
with open(os.path.expanduser(os.path.expandvars
302
(config[u"secfile"])),
317
(config["secfile"])),
303
318
"rb") as secfile:
304
319
self.secret = secfile.read()
306
#XXX Need to allow secret on demand!
307
raise TypeError(u"No secret or secfile for client %s"
321
raise TypeError("No secret or secfile for client %s"
309
self.host = config.get(u"host", u"")
323
self.host = config.get("host", "")
310
324
self.created = datetime.datetime.utcnow()
311
325
self.enabled = False
326
self.last_approval_request = None
312
327
self.last_enabled = None
313
328
self.last_checked_ok = None
314
self.timeout = string_to_delta(config[u"timeout"])
315
self.interval = string_to_delta(config[u"interval"])
329
self.timeout = string_to_delta(config["timeout"])
330
self.interval = string_to_delta(config["interval"])
316
331
self.disable_hook = disable_hook
317
332
self.checker = None
318
333
self.checker_initiator_tag = None
319
334
self.disable_initiator_tag = None
320
335
self.checker_callback_tag = None
321
self.checker_command = config[u"checker"]
336
self.checker_command = config["checker"]
322
337
self.current_checker_command = None
323
338
self.last_connect = None
339
self._approved = None
340
self.approved_by_default = config.get("approved_by_default",
324
342
self.approvals_pending = 0
325
self._approved = None
326
self.approved_by_default = config.get(u"approved_by_default",
328
self.approved_delay = string_to_delta(
329
config[u"approved_delay"])
330
self.approved_duration = string_to_delta(
331
config[u"approved_duration"])
343
self.approval_delay = string_to_delta(
344
config["approval_delay"])
345
self.approval_duration = string_to_delta(
346
config["approval_duration"])
332
347
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
334
349
def send_changedstate(self):
335
350
self.changedstate.acquire()
336
351
self.changedstate.notify_all()
444
462
command = self.checker_command % self.host
445
463
except TypeError:
446
464
# Escape attributes for the shell
447
escaped_attrs = dict((key,
448
re.escape(unicode(str(val),
452
vars(self).iteritems())
465
escaped_attrs = dict(
467
re.escape(unicode(str(getattr(self, attr, "")),
471
self.runtime_expansions)
454
474
command = self.checker_command % escaped_attrs
455
475
except TypeError, error:
456
logger.error(u'Could not format string "%s":'
457
u' %s', self.checker_command, error)
476
logger.error('Could not format string "%s":'
477
' %s', self.checker_command, error)
458
478
return True # Try again later
459
479
self.current_checker_command = command
461
logger.info(u"Starting checker %r for %s",
481
logger.info("Starting checker %r for %s",
462
482
command, self.name)
463
483
# We don't need to redirect stdout and stderr, since
464
484
# in normal mode, that is already done by daemon(),
516
536
# Encoding deeply encoded byte arrays is not supported yet by the
517
537
# "Set" method, so we fail early here:
518
if byte_arrays and signature != u"ay":
519
raise ValueError(u"Byte arrays not supported for non-'ay'"
520
u" signature %r" % signature)
538
if byte_arrays and signature != "ay":
539
raise ValueError("Byte arrays not supported for non-'ay'"
540
" signature %r" % signature)
521
541
def decorator(func):
522
542
func._dbus_is_property = True
523
543
func._dbus_interface = dbus_interface
524
544
func._dbus_signature = signature
525
545
func._dbus_access = access
526
546
func._dbus_name = func.__name__
527
if func._dbus_name.endswith(u"_dbus_property"):
547
if func._dbus_name.endswith("_dbus_property"):
528
548
func._dbus_name = func._dbus_name[:-14]
529
func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
549
func._dbus_get_args_options = {'byte_arrays': byte_arrays }
586
606
# No such property
587
raise DBusPropertyNotFound(self.dbus_object_path + u":"
588
+ interface_name + u"."
607
raise DBusPropertyNotFound(self.dbus_object_path + ":"
608
+ interface_name + "."
591
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
611
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
593
613
def Get(self, interface_name, property_name):
594
614
"""Standard D-Bus property Get() method, see D-Bus standard.
596
616
prop = self._get_dbus_property(interface_name, property_name)
597
if prop._dbus_access == u"write":
617
if prop._dbus_access == "write":
598
618
raise DBusPropertyAccessException(property_name)
600
if not hasattr(value, u"variant_level"):
620
if not hasattr(value, "variant_level"):
602
622
return type(value)(value, variant_level=value.variant_level+1)
604
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
624
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
605
625
def Set(self, interface_name, property_name, value):
606
626
"""Standard D-Bus property Set() method, see D-Bus standard.
608
628
prop = self._get_dbus_property(interface_name, property_name)
609
if prop._dbus_access == u"read":
629
if prop._dbus_access == "read":
610
630
raise DBusPropertyAccessException(property_name)
611
if prop._dbus_get_args_options[u"byte_arrays"]:
631
if prop._dbus_get_args_options["byte_arrays"]:
612
632
# The byte_arrays option is not supported yet on
613
633
# signatures other than "ay".
614
if prop._dbus_signature != u"ay":
634
if prop._dbus_signature != "ay":
616
636
value = dbus.ByteArray(''.join(unichr(byte)
617
637
for byte in value))
620
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
621
out_signature=u"a{sv}")
640
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
641
out_signature="a{sv}")
622
642
def GetAll(self, interface_name):
623
643
"""Standard D-Bus property GetAll() method, see D-Bus
655
675
document = xml.dom.minidom.parseString(xmlstring)
656
676
def make_tag(document, name, prop):
657
e = document.createElement(u"property")
658
e.setAttribute(u"name", name)
659
e.setAttribute(u"type", prop._dbus_signature)
660
e.setAttribute(u"access", prop._dbus_access)
677
e = document.createElement("property")
678
e.setAttribute("name", name)
679
e.setAttribute("type", prop._dbus_signature)
680
e.setAttribute("access", prop._dbus_access)
662
for if_tag in document.getElementsByTagName(u"interface"):
682
for if_tag in document.getElementsByTagName("interface"):
663
683
for tag in (make_tag(document, name, prop)
665
685
in self._get_all_dbus_properties()
666
686
if prop._dbus_interface
667
== if_tag.getAttribute(u"name")):
687
== if_tag.getAttribute("name")):
668
688
if_tag.appendChild(tag)
669
689
# Add the names to the return values for the
670
690
# "org.freedesktop.DBus.Properties" methods
671
if (if_tag.getAttribute(u"name")
672
== u"org.freedesktop.DBus.Properties"):
673
for cn in if_tag.getElementsByTagName(u"method"):
674
if cn.getAttribute(u"name") == u"Get":
675
for arg in cn.getElementsByTagName(u"arg"):
676
if (arg.getAttribute(u"direction")
678
arg.setAttribute(u"name", u"value")
679
elif cn.getAttribute(u"name") == u"GetAll":
680
for arg in cn.getElementsByTagName(u"arg"):
681
if (arg.getAttribute(u"direction")
683
arg.setAttribute(u"name", u"props")
684
xmlstring = document.toxml(u"utf-8")
691
if (if_tag.getAttribute("name")
692
== "org.freedesktop.DBus.Properties"):
693
for cn in if_tag.getElementsByTagName("method"):
694
if cn.getAttribute("name") == "Get":
695
for arg in cn.getElementsByTagName("arg"):
696
if (arg.getAttribute("direction")
698
arg.setAttribute("name", "value")
699
elif cn.getAttribute("name") == "GetAll":
700
for arg in cn.getElementsByTagName("arg"):
701
if (arg.getAttribute("direction")
703
arg.setAttribute("name", "props")
704
xmlstring = document.toxml("utf-8")
685
705
document.unlink()
686
706
except (AttributeError, xml.dom.DOMException,
687
707
xml.parsers.expat.ExpatError), error:
688
logger.error(u"Failed to override Introspection method",
708
logger.error("Failed to override Introspection method",
697
717
dbus_object_path: dbus.ObjectPath
698
718
bus: dbus.SystemBus()
721
runtime_expansions = (Client.runtime_expansions
722
+ ("dbus_object_path",))
700
724
# dbus.service.Object doesn't use super(), so we can't either.
702
726
def __init__(self, bus = None, *args, **kwargs):
727
self._approvals_pending = 0
704
729
Client.__init__(self, *args, **kwargs)
705
730
# Only now, when this client is initialized, can it show up on
732
client_object_name = unicode(self.name).translate(
707
735
self.dbus_object_path = (dbus.ObjectPath
709
+ self.name.replace(u".", u"_")))
736
("/clients/" + client_object_name))
710
737
DBusObjectWithProperties.__init__(self, self.bus,
711
738
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
714
757
def _datetime_to_dbus(dt, variant_level=0):
717
760
variant_level=variant_level)
719
762
def enable(self):
720
oldstate = getattr(self, u"enabled", False)
763
oldstate = getattr(self, "enabled", False)
721
764
r = Client.enable(self)
722
765
if oldstate != self.enabled:
723
766
# Emit D-Bus signals
724
self.PropertyChanged(dbus.String(u"enabled"),
767
self.PropertyChanged(dbus.String("Enabled"),
725
768
dbus.Boolean(True, variant_level=1))
726
769
self.PropertyChanged(
727
dbus.String(u"last_enabled"),
770
dbus.String("LastEnabled"),
728
771
self._datetime_to_dbus(self.last_enabled,
729
772
variant_level=1))
732
775
def disable(self, quiet = False):
733
oldstate = getattr(self, u"enabled", False)
776
oldstate = getattr(self, "enabled", False)
734
777
r = Client.disable(self, quiet=quiet)
735
778
if not quiet and oldstate != self.enabled:
736
779
# Emit D-Bus signal
737
self.PropertyChanged(dbus.String(u"enabled"),
780
self.PropertyChanged(dbus.String("Enabled"),
738
781
dbus.Boolean(False, variant_level=1))
791
843
# Emit D-Bus signal
792
844
self.CheckerStarted(self.current_checker_command)
793
845
self.PropertyChanged(
794
dbus.String(u"checker_running"),
846
dbus.String("CheckerRunning"),
795
847
dbus.Boolean(True, variant_level=1))
798
850
def stop_checker(self, *args, **kwargs):
799
old_checker = getattr(self, u"checker", None)
851
old_checker = getattr(self, "checker", None)
800
852
r = Client.stop_checker(self, *args, **kwargs)
801
853
if (old_checker is not None
802
and getattr(self, u"checker", None) is None):
803
self.PropertyChanged(dbus.String(u"checker_running"),
854
and getattr(self, "checker", None) is None):
855
self.PropertyChanged(dbus.String("CheckerRunning"),
804
856
dbus.Boolean(False, variant_level=1))
811
863
def approve(self, value=True):
864
self.send_changedstate()
812
865
self._approved = value
813
gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration, self._reset_approved))
815
def approved_pending(self):
816
return self.approvals_pending > 0
866
gobject.timeout_add(self._timedelta_to_milliseconds
867
(self.approval_duration),
868
self._reset_approved)
819
871
## D-Bus methods, signals & properties
820
_interface = u"se.bsnet.fukt.Mandos.Client"
872
_interface = "se.bsnet.fukt.Mandos.Client"
824
876
# CheckerCompleted - signal
825
@dbus.service.signal(_interface, signature=u"nxs")
877
@dbus.service.signal(_interface, signature="nxs")
826
878
def CheckerCompleted(self, exitcode, waitstatus, command):
830
882
# CheckerStarted - signal
831
@dbus.service.signal(_interface, signature=u"s")
883
@dbus.service.signal(_interface, signature="s")
832
884
def CheckerStarted(self, command):
836
888
# PropertyChanged - signal
837
@dbus.service.signal(_interface, signature=u"sv")
889
@dbus.service.signal(_interface, signature="sv")
838
890
def PropertyChanged(self, property, value):
897
# approved_pending - property
898
@dbus_service_property(_interface, signature=u"b", access=u"read")
899
def approved_pending_dbus_property(self):
900
return dbus.Boolean(self.approved_pending())
902
# approved_by_default - property
903
@dbus_service_property(_interface, signature=u"b",
905
def approved_by_default_dbus_property(self):
906
return dbus.Boolean(self.approved_by_default)
908
# approved_delay - property
909
@dbus_service_property(_interface, signature=u"t",
911
def approved_delay_dbus_property(self):
912
return dbus.UInt64(self.approved_delay_milliseconds())
914
# approved_duration - property
915
@dbus_service_property(_interface, signature=u"t",
917
def approved_duration_dbus_property(self):
918
return dbus.UInt64(self._timedelta_to_milliseconds(
919
self.approved_duration))
922
@dbus_service_property(_interface, signature=u"s", access=u"read")
923
def name_dbus_property(self):
952
# ApprovalPending - property
953
@dbus_service_property(_interface, signature="b", access="read")
954
def ApprovalPending_dbus_property(self):
955
return dbus.Boolean(bool(self.approvals_pending))
957
# ApprovedByDefault - property
958
@dbus_service_property(_interface, signature="b",
960
def ApprovedByDefault_dbus_property(self, value=None):
961
if value is None: # get
962
return dbus.Boolean(self.approved_by_default)
963
self.approved_by_default = bool(value)
965
self.PropertyChanged(dbus.String("ApprovedByDefault"),
966
dbus.Boolean(value, variant_level=1))
968
# ApprovalDelay - property
969
@dbus_service_property(_interface, signature="t",
971
def ApprovalDelay_dbus_property(self, value=None):
972
if value is None: # get
973
return dbus.UInt64(self.approval_delay_milliseconds())
974
self.approval_delay = datetime.timedelta(0, 0, 0, value)
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
977
dbus.UInt64(value, variant_level=1))
979
# ApprovalDuration - property
980
@dbus_service_property(_interface, signature="t",
982
def ApprovalDuration_dbus_property(self, value=None):
983
if value is None: # get
984
return dbus.UInt64(self._timedelta_to_milliseconds(
985
self.approval_duration))
986
self.approval_duration = datetime.timedelta(0, 0, 0, value)
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
989
dbus.UInt64(value, variant_level=1))
992
@dbus_service_property(_interface, signature="s", access="read")
993
def Name_dbus_property(self):
924
994
return dbus.String(self.name)
926
# fingerprint - property
927
@dbus_service_property(_interface, signature=u"s", access=u"read")
928
def fingerprint_dbus_property(self):
996
# Fingerprint - property
997
@dbus_service_property(_interface, signature="s", access="read")
998
def Fingerprint_dbus_property(self):
929
999
return dbus.String(self.fingerprint)
932
@dbus_service_property(_interface, signature=u"s",
934
def host_dbus_property(self, value=None):
1002
@dbus_service_property(_interface, signature="s",
1004
def Host_dbus_property(self, value=None):
935
1005
if value is None: # get
936
1006
return dbus.String(self.host)
937
1007
self.host = value
938
1008
# Emit D-Bus signal
939
self.PropertyChanged(dbus.String(u"host"),
1009
self.PropertyChanged(dbus.String("Host"),
940
1010
dbus.String(value, variant_level=1))
943
@dbus_service_property(_interface, signature=u"s", access=u"read")
944
def created_dbus_property(self):
1012
# Created - property
1013
@dbus_service_property(_interface, signature="s", access="read")
1014
def Created_dbus_property(self):
945
1015
return dbus.String(self._datetime_to_dbus(self.created))
947
# last_enabled - property
948
@dbus_service_property(_interface, signature=u"s", access=u"read")
949
def last_enabled_dbus_property(self):
1017
# LastEnabled - property
1018
@dbus_service_property(_interface, signature="s", access="read")
1019
def LastEnabled_dbus_property(self):
950
1020
if self.last_enabled is None:
951
return dbus.String(u"")
1021
return dbus.String("")
952
1022
return dbus.String(self._datetime_to_dbus(self.last_enabled))
955
@dbus_service_property(_interface, signature=u"b",
957
def enabled_dbus_property(self, value=None):
1024
# Enabled - property
1025
@dbus_service_property(_interface, signature="b",
1027
def Enabled_dbus_property(self, value=None):
958
1028
if value is None: # get
959
1029
return dbus.Boolean(self.enabled)
965
# last_checked_ok - property
966
@dbus_service_property(_interface, signature=u"s",
968
def last_checked_ok_dbus_property(self, value=None):
1035
# LastCheckedOK - property
1036
@dbus_service_property(_interface, signature="s",
1038
def LastCheckedOK_dbus_property(self, value=None):
969
1039
if value is not None:
970
1040
self.checked_ok()
972
1042
if self.last_checked_ok is None:
973
return dbus.String(u"")
1043
return dbus.String("")
974
1044
return dbus.String(self._datetime_to_dbus(self
975
1045
.last_checked_ok))
978
@dbus_service_property(_interface, signature=u"t",
980
def timeout_dbus_property(self, value=None):
1047
# LastApprovalRequest - property
1048
@dbus_service_property(_interface, signature="s", access="read")
1049
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))
1056
# Timeout - property
1057
@dbus_service_property(_interface, signature="t",
1059
def Timeout_dbus_property(self, value=None):
981
1060
if value is None: # get
982
1061
return dbus.UInt64(self.timeout_milliseconds())
983
1062
self.timeout = datetime.timedelta(0, 0, 0, value)
984
1063
# Emit D-Bus signal
985
self.PropertyChanged(dbus.String(u"timeout"),
1064
self.PropertyChanged(dbus.String("Timeout"),
986
1065
dbus.UInt64(value, variant_level=1))
987
if getattr(self, u"disable_initiator_tag", None) is None:
1066
if getattr(self, "disable_initiator_tag", None) is None:
989
1068
# Reschedule timeout
990
1069
gobject.source_remove(self.disable_initiator_tag)
1002
1081
self.disable_initiator_tag = (gobject.timeout_add
1003
1082
(time_to_die, self.disable))
1005
# interval - property
1006
@dbus_service_property(_interface, signature=u"t",
1007
access=u"readwrite")
1008
def interval_dbus_property(self, value=None):
1084
# Interval - property
1085
@dbus_service_property(_interface, signature="t",
1087
def Interval_dbus_property(self, value=None):
1009
1088
if value is None: # get
1010
1089
return dbus.UInt64(self.interval_milliseconds())
1011
1090
self.interval = datetime.timedelta(0, 0, 0, value)
1012
1091
# Emit D-Bus signal
1013
self.PropertyChanged(dbus.String(u"interval"),
1092
self.PropertyChanged(dbus.String("Interval"),
1014
1093
dbus.UInt64(value, variant_level=1))
1015
if getattr(self, u"checker_initiator_tag", None) is None:
1094
if getattr(self, "checker_initiator_tag", None) is None:
1017
1096
# Reschedule checker run
1018
1097
gobject.source_remove(self.checker_initiator_tag)
1020
1099
(value, self.start_checker))
1021
1100
self.start_checker() # Start one now, too
1023
# checker - property
1024
@dbus_service_property(_interface, signature=u"s",
1025
access=u"readwrite")
1026
def checker_dbus_property(self, value=None):
1102
# Checker - property
1103
@dbus_service_property(_interface, signature="s",
1105
def Checker_dbus_property(self, value=None):
1027
1106
if value is None: # get
1028
1107
return dbus.String(self.checker_command)
1029
1108
self.checker_command = value
1030
1109
# Emit D-Bus signal
1031
self.PropertyChanged(dbus.String(u"checker"),
1110
self.PropertyChanged(dbus.String("Checker"),
1032
1111
dbus.String(self.checker_command,
1033
1112
variant_level=1))
1035
# checker_running - property
1036
@dbus_service_property(_interface, signature=u"b",
1037
access=u"readwrite")
1038
def checker_running_dbus_property(self, value=None):
1114
# CheckerRunning - property
1115
@dbus_service_property(_interface, signature="b",
1117
def CheckerRunning_dbus_property(self, value=None):
1039
1118
if value is None: # get
1040
1119
return dbus.Boolean(self.checker is not None)
1106
1185
# no X.509 keys are added to it. Therefore, we can use it
1107
1186
# here despite using OpenPGP certificates.
1109
#priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1110
# u"+AES-256-CBC", u"+SHA1",
1111
# u"+COMP-NULL", u"+CTYPE-OPENPGP",
1188
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
# "+AES-256-CBC", "+SHA1",
1190
# "+COMP-NULL", "+CTYPE-OPENPGP",
1113
1192
# Use a fallback default, since this MUST be set.
1114
1193
priority = self.server.gnutls_priority
1115
1194
if priority is None:
1116
priority = u"NORMAL"
1117
1196
(gnutls.library.functions
1118
1197
.gnutls_priority_set_direct(session._c_object,
1119
1198
priority, None))
1121
1200
# Start communication using the Mandos protocol
1122
1201
# Get protocol number
1123
1202
line = self.request.makefile().readline()
1124
logger.debug(u"Protocol version: %r", line)
1203
logger.debug("Protocol version: %r", line)
1126
1205
if int(line.strip().split()[0]) > 1:
1127
1206
raise RuntimeError
1128
1207
except (ValueError, IndexError, RuntimeError), error:
1129
logger.error(u"Unknown protocol version: %s", error)
1208
logger.error("Unknown protocol version: %s", error)
1132
1211
# Start GnuTLS connection
1134
1213
session.handshake()
1135
1214
except gnutls.errors.GNUTLSError, error:
1136
logger.warning(u"Handshake failed: %s", error)
1215
logger.warning("Handshake failed: %s", error)
1137
1216
# Do not run session.bye() here: the session is not
1138
1217
# established. Just abandon the request.
1140
logger.debug(u"Handshake succeeded")
1219
logger.debug("Handshake succeeded")
1142
1221
approval_required = False
1155
1234
except KeyError:
1158
if client.approved_delay:
1159
delay = client.approved_delay
1237
if client.approval_delay:
1238
delay = client.approval_delay
1160
1239
client.approvals_pending += 1
1161
1240
approval_required = True
1164
1243
if not client.enabled:
1165
logger.warning(u"Client %s is disabled",
1244
logger.warning("Client %s is disabled",
1167
1246
if self.server.use_dbus:
1168
1247
# Emit D-Bus signal
1169
1248
client.Rejected("Disabled")
1172
if client._approved or not client.approved_delay:
1251
if client._approved or not client.approval_delay:
1173
1252
#We are approved or approval is disabled
1175
1254
elif client._approved is None:
1176
logger.info(u"Client %s need approval",
1255
logger.info("Client %s needs approval",
1178
1257
if self.server.use_dbus:
1179
1258
# Emit D-Bus signal
1180
1259
client.NeedApproval(
1181
client.approved_delay_milliseconds(),
1260
client.approval_delay_milliseconds(),
1182
1261
client.approved_by_default)
1184
logger.warning(u"Client %s was not approved",
1263
logger.warning("Client %s was not approved",
1186
1265
if self.server.use_dbus:
1187
1266
# Emit D-Bus signal
1188
client.Rejected("Disapproved")
1267
client.Rejected("Denied")
1191
1270
#wait until timeout or approved
1348
1433
bind to an address or port if they were not specified."""
1349
1434
if self.interface is not None:
1350
1435
if SO_BINDTODEVICE is None:
1351
logger.error(u"SO_BINDTODEVICE does not exist;"
1352
u" cannot bind to interface %s",
1436
logger.error("SO_BINDTODEVICE does not exist;"
1437
" cannot bind to interface %s",
1353
1438
self.interface)
1356
1441
self.socket.setsockopt(socket.SOL_SOCKET,
1357
1442
SO_BINDTODEVICE,
1358
1443
str(self.interface
1360
1445
except socket.error, error:
1361
1446
if error[0] == errno.EPERM:
1362
logger.error(u"No permission to"
1363
u" bind to interface %s",
1447
logger.error("No permission to"
1448
" bind to interface %s",
1364
1449
self.interface)
1365
1450
elif error[0] == errno.ENOPROTOOPT:
1366
logger.error(u"SO_BINDTODEVICE not available;"
1367
u" cannot bind to interface %s",
1451
logger.error("SO_BINDTODEVICE not available;"
1452
" cannot bind to interface %s",
1368
1453
self.interface)
1427
1512
def handle_ipc(self, source, condition, parent_pipe=None,
1428
1513
client_object=None):
1429
1514
condition_names = {
1430
gobject.IO_IN: u"IN", # There is data to read.
1431
gobject.IO_OUT: u"OUT", # Data can be written (without
1515
gobject.IO_IN: "IN", # There is data to read.
1516
gobject.IO_OUT: "OUT", # Data can be written (without
1433
gobject.IO_PRI: u"PRI", # There is urgent data to read.
1434
gobject.IO_ERR: u"ERR", # Error condition.
1435
gobject.IO_HUP: u"HUP" # Hung up (the connection has been
1518
gobject.IO_PRI: "PRI", # There is urgent data to read.
1519
gobject.IO_ERR: "ERR", # Error condition.
1520
gobject.IO_HUP: "HUP" # Hung up (the connection has been
1436
1521
# broken, usually for pipes and
1490
1571
parent_pipe.send(('function',))
1492
1573
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1494
1575
if command == 'setattr':
1495
1576
attrname = request[1]
1496
1577
value = request[2]
1497
1578
setattr(client_object, attrname, value)
1502
1583
def string_to_delta(interval):
1503
1584
"""Parse a string and return a datetime.timedelta
1505
>>> string_to_delta(u'7d')
1586
>>> string_to_delta('7d')
1506
1587
datetime.timedelta(7)
1507
>>> string_to_delta(u'60s')
1588
>>> string_to_delta('60s')
1508
1589
datetime.timedelta(0, 60)
1509
>>> string_to_delta(u'60m')
1590
>>> string_to_delta('60m')
1510
1591
datetime.timedelta(0, 3600)
1511
>>> string_to_delta(u'24h')
1592
>>> string_to_delta('24h')
1512
1593
datetime.timedelta(1)
1513
>>> string_to_delta(u'1w')
1594
>>> string_to_delta('1w')
1514
1595
datetime.timedelta(7)
1515
>>> string_to_delta(u'5m 30s')
1596
>>> string_to_delta('5m 30s')
1516
1597
datetime.timedelta(0, 330)
1518
1599
timevalue = datetime.timedelta(0)
1521
1602
suffix = unicode(s[-1])
1522
1603
value = int(s[:-1])
1524
1605
delta = datetime.timedelta(value)
1525
elif suffix == u"s":
1526
1607
delta = datetime.timedelta(0, value)
1527
elif suffix == u"m":
1528
1609
delta = datetime.timedelta(0, 0, 0, 0, value)
1529
elif suffix == u"h":
1530
1611
delta = datetime.timedelta(0, 0, 0, 0, 0, value)
1531
elif suffix == u"w":
1532
1613
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1534
raise ValueError(u"Unknown suffix %r" % suffix)
1615
raise ValueError("Unknown suffix %r" % suffix)
1535
1616
except (ValueError, IndexError), e:
1536
raise ValueError(e.message)
1617
raise ValueError(*(e.args))
1537
1618
timevalue += delta
1538
1619
return timevalue
1545
1626
global if_nametoindex
1547
1628
if_nametoindex = (ctypes.cdll.LoadLibrary
1548
(ctypes.util.find_library(u"c"))
1629
(ctypes.util.find_library("c"))
1549
1630
.if_nametoindex)
1550
1631
except (OSError, AttributeError):
1551
logger.warning(u"Doing if_nametoindex the hard way")
1632
logger.warning("Doing if_nametoindex the hard way")
1552
1633
def if_nametoindex(interface):
1553
1634
"Get an interface index the hard way, i.e. using fcntl()"
1554
1635
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1555
1636
with contextlib.closing(socket.socket()) as s:
1556
1637
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1557
struct.pack(str(u"16s16x"),
1638
struct.pack(str("16s16x"),
1559
interface_index = struct.unpack(str(u"I"),
1640
interface_index = struct.unpack(str("I"),
1560
1641
ifreq[16:20])[0]
1561
1642
return interface_index
1562
1643
return if_nametoindex(interface)
1593
1674
# Parsing of options, both command line and config file
1595
1676
parser = optparse.OptionParser(version = "%%prog %s" % version)
1596
parser.add_option("-i", u"--interface", type=u"string",
1597
metavar="IF", help=u"Bind to interface IF")
1598
parser.add_option("-a", u"--address", type=u"string",
1599
help=u"Address to listen for requests on")
1600
parser.add_option("-p", u"--port", type=u"int",
1601
help=u"Port number to receive requests on")
1602
parser.add_option("--check", action=u"store_true",
1603
help=u"Run self-test")
1604
parser.add_option("--debug", action=u"store_true",
1605
help=u"Debug mode; run in foreground and log to"
1607
parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1608
u" priority string (see GnuTLS documentation)")
1609
parser.add_option("--servicename", type=u"string",
1610
metavar=u"NAME", help=u"Zeroconf service name")
1611
parser.add_option("--configdir", type=u"string",
1612
default=u"/etc/mandos", metavar=u"DIR",
1613
help=u"Directory to search for configuration"
1615
parser.add_option("--no-dbus", action=u"store_false",
1616
dest=u"use_dbus", help=u"Do not provide D-Bus"
1617
u" system bus interface")
1618
parser.add_option("--no-ipv6", action=u"store_false",
1619
dest=u"use_ipv6", help=u"Do not use IPv6")
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")
1620
1703
options = parser.parse_args()[0]
1622
1705
if options.check:
1627
1710
# Default values for config file for server-global settings
1628
server_defaults = { u"interface": u"",
1633
u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1634
u"servicename": u"Mandos",
1635
u"use_dbus": u"True",
1636
u"use_ipv6": u"True",
1711
server_defaults = { "interface": "",
1716
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1717
"servicename": "Mandos",
1639
1723
# Parse config file for server-global settings
1640
1724
server_config = configparser.SafeConfigParser(server_defaults)
1641
1725
del server_defaults
1642
1726
server_config.read(os.path.join(options.configdir,
1644
1728
# Convert the SafeConfigParser object to a dict
1645
1729
server_settings = server_config.defaults()
1646
1730
# Use the appropriate methods on the non-string config options
1647
for option in (u"debug", u"use_dbus", u"use_ipv6"):
1648
server_settings[option] = server_config.getboolean(u"DEFAULT",
1731
for option in ("debug", "use_dbus", "use_ipv6"):
1732
server_settings[option] = server_config.getboolean("DEFAULT",
1650
1734
if server_settings["port"]:
1651
server_settings["port"] = server_config.getint(u"DEFAULT",
1735
server_settings["port"] = server_config.getint("DEFAULT",
1653
1737
del server_config
1655
1739
# Override the settings from the config file with command line
1656
1740
# options, if set.
1657
for option in (u"interface", u"address", u"port", u"debug",
1658
u"priority", u"servicename", u"configdir",
1659
u"use_dbus", u"use_ipv6"):
1741
for option in ("interface", "address", "port", "debug",
1742
"priority", "servicename", "configdir",
1743
"use_dbus", "use_ipv6", "debuglevel"):
1660
1744
value = getattr(options, option)
1661
1745
if value is not None:
1662
1746
server_settings[option] = value
1670
1754
##################################################################
1672
1756
# For convenience
1673
debug = server_settings[u"debug"]
1674
use_dbus = server_settings[u"use_dbus"]
1675
use_ipv6 = server_settings[u"use_ipv6"]
1678
syslogger.setLevel(logging.WARNING)
1679
console.setLevel(logging.WARNING)
1681
if server_settings[u"servicename"] != u"Mandos":
1757
debug = server_settings["debug"]
1758
debuglevel = server_settings["debuglevel"]
1759
use_dbus = server_settings["use_dbus"]
1760
use_ipv6 = server_settings["use_ipv6"]
1762
if server_settings["servicename"] != "Mandos":
1682
1763
syslogger.setFormatter(logging.Formatter
1683
(u'Mandos (%s) [%%(process)d]:'
1684
u' %%(levelname)s: %%(message)s'
1685
% server_settings[u"servicename"]))
1764
('Mandos (%s) [%%(process)d]:'
1765
' %%(levelname)s: %%(message)s'
1766
% server_settings["servicename"]))
1687
1768
# Parse config file with clients
1688
client_defaults = { u"timeout": u"1h",
1690
u"checker": u"fping -q -- %%(host)s",
1692
u"approved_delay": u"5m",
1693
u"approved_duration": u"1s",
1769
client_defaults = { "timeout": "1h",
1771
"checker": "fping -q -- %%(host)s",
1773
"approval_delay": "0s",
1774
"approval_duration": "1s",
1695
1776
client_config = configparser.SafeConfigParser(client_defaults)
1696
client_config.read(os.path.join(server_settings[u"configdir"],
1777
client_config.read(os.path.join(server_settings["configdir"],
1699
1780
global mandos_dbus_service
1700
1781
mandos_dbus_service = None
1702
tcp_server = MandosServer((server_settings[u"address"],
1703
server_settings[u"port"]),
1783
tcp_server = MandosServer((server_settings["address"],
1784
server_settings["port"]),
1705
interface=server_settings[u"interface"],
1786
interface=(server_settings["interface"]
1706
1788
use_ipv6=use_ipv6,
1707
1789
gnutls_priority=
1708
server_settings[u"priority"],
1790
server_settings["priority"],
1709
1791
use_dbus=use_dbus)
1710
pidfilename = u"/var/run/mandos.pid"
1712
pidfile = open(pidfilename, u"w")
1714
logger.error(u"Could not open file %r", pidfilename)
1793
pidfilename = "/var/run/mandos.pid"
1795
pidfile = open(pidfilename, "w")
1797
logger.error("Could not open file %r", pidfilename)
1717
uid = pwd.getpwnam(u"_mandos").pw_uid
1718
gid = pwd.getpwnam(u"_mandos").pw_gid
1800
uid = pwd.getpwnam("_mandos").pw_uid
1801
gid = pwd.getpwnam("_mandos").pw_gid
1719
1802
except KeyError:
1721
uid = pwd.getpwnam(u"mandos").pw_uid
1722
gid = pwd.getpwnam(u"mandos").pw_gid
1804
uid = pwd.getpwnam("mandos").pw_uid
1805
gid = pwd.getpwnam("mandos").pw_gid
1723
1806
except KeyError:
1725
uid = pwd.getpwnam(u"nobody").pw_uid
1726
gid = pwd.getpwnam(u"nobody").pw_gid
1808
uid = pwd.getpwnam("nobody").pw_uid
1809
gid = pwd.getpwnam("nobody").pw_gid
1727
1810
except KeyError:
1734
1817
if error[0] != errno.EPERM:
1737
# Enable all possible GnuTLS debugging
1820
if not debug and not debuglevel:
1821
syslogger.setLevel(logging.WARNING)
1822
console.setLevel(logging.WARNING)
1824
level = getattr(logging, debuglevel.upper())
1825
syslogger.setLevel(level)
1826
console.setLevel(level)
1829
# Enable all possible GnuTLS debugging
1739
1831
# "Use a log level over 10 to enable all debugging options."
1740
1832
# - GnuTLS manual
1741
1833
gnutls.library.functions.gnutls_global_set_log_level(11)
1743
1835
@gnutls.library.types.gnutls_log_func
1744
1836
def debug_gnutls(level, string):
1745
logger.debug(u"GnuTLS: %s", string[:-1])
1837
logger.debug("GnuTLS: %s", string[:-1])
1747
1839
(gnutls.library.functions
1748
1840
.gnutls_global_set_log_function(debug_gnutls))
1842
# Redirect stdin so all checkers get /dev/null
1843
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1844
os.dup2(null, sys.stdin.fileno())
1848
# No console logging
1849
logger.removeHandler(console)
1851
# Need to fork before connecting to D-Bus
1853
# Close all input and output, do double fork, etc.
1750
1856
global main_loop
1751
1857
# From the Avahi example code
1755
1861
# End of Avahi example code
1758
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1864
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1759
1865
bus, do_not_queue=True)
1760
1866
except dbus.exceptions.NameExistsException, e:
1761
logger.error(unicode(e) + u", disabling D-Bus")
1867
logger.error(unicode(e) + ", disabling D-Bus")
1762
1868
use_dbus = False
1763
server_settings[u"use_dbus"] = False
1869
server_settings["use_dbus"] = False
1764
1870
tcp_server.use_dbus = False
1765
1871
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1766
service = AvahiService(name = server_settings[u"servicename"],
1767
servicetype = u"_mandos._tcp",
1872
service = AvahiService(name = server_settings["servicename"],
1873
servicetype = "_mandos._tcp",
1768
1874
protocol = protocol, bus = bus)
1769
1875
if server_settings["interface"]:
1770
1876
service.interface = (if_nametoindex
1771
(str(server_settings[u"interface"])))
1877
(str(server_settings["interface"])))
1773
1879
global multiprocessing_manager
1774
1880
multiprocessing_manager = multiprocessing.Manager()
1794
1900
client_config, section)))
1795
1901
for section in client_config.sections()))
1796
1902
if not tcp_server.clients:
1797
logger.warning(u"No clients defined")
1800
# Redirect stdin so all checkers get /dev/null
1801
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1802
os.dup2(null, sys.stdin.fileno())
1806
# No console logging
1807
logger.removeHandler(console)
1808
# Close all input and output, do double fork, etc.
1814
pidfile.write(str(pid) + "\n")
1817
logger.error(u"Could not write to file %r with PID %d",
1820
# "pidfile" was never created
1903
logger.warning("No clients defined")
1909
pidfile.write(str(pid) + "\n".encode("utf-8"))
1912
logger.error("Could not write to file %r with PID %d",
1915
# "pidfile" was never created
1825
1919
signal.signal(signal.SIGINT, signal.SIG_IGN)
1826
1921
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1827
1922
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1830
1925
class MandosDBusService(dbus.service.Object):
1831
1926
"""A D-Bus proxy object"""
1832
1927
def __init__(self):
1833
dbus.service.Object.__init__(self, bus, u"/")
1834
_interface = u"se.bsnet.fukt.Mandos"
1928
dbus.service.Object.__init__(self, bus, "/")
1929
_interface = "se.bsnet.fukt.Mandos"
1836
@dbus.service.signal(_interface, signature=u"o")
1931
@dbus.service.signal(_interface, signature="o")
1837
1932
def ClientAdded(self, objpath):
1841
@dbus.service.signal(_interface, signature=u"ss")
1936
@dbus.service.signal(_interface, signature="ss")
1842
1937
def ClientNotFound(self, fingerprint, address):
1846
@dbus.service.signal(_interface, signature=u"os")
1941
@dbus.service.signal(_interface, signature="os")
1847
1942
def ClientRemoved(self, objpath, name):
1851
@dbus.service.method(_interface, out_signature=u"ao")
1946
@dbus.service.method(_interface, out_signature="ao")
1852
1947
def GetAllClients(self):
1854
1949
return dbus.Array(c.dbus_object_path
1855
1950
for c in tcp_server.clients)
1857
1952
@dbus.service.method(_interface,
1858
out_signature=u"a{oa{sv}}")
1953
out_signature="a{oa{sv}}")
1859
1954
def GetAllClientsWithProperties(self):
1861
1956
return dbus.Dictionary(
1862
((c.dbus_object_path, c.GetAll(u""))
1957
((c.dbus_object_path, c.GetAll(""))
1863
1958
for c in tcp_server.clients),
1864
signature=u"oa{sv}")
1866
@dbus.service.method(_interface, in_signature=u"o")
1961
@dbus.service.method(_interface, in_signature="o")
1867
1962
def RemoveClient(self, object_path):
1869
1964
for c in tcp_server.clients: