81
82
SO_BINDTODEVICE = None
86
#logger = logging.getLogger(u'mandos')
87
logger = logging.Logger(u'mandos')
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
88
89
syslogger = (logging.handlers.SysLogHandler
89
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
90
address = "/dev/log"))
91
address = str("/dev/log")))
91
92
syslogger.setFormatter(logging.Formatter
92
(u'Mandos [%(process)d]: %(levelname)s:'
93
('Mandos [%(process)d]: %(levelname)s:'
94
95
logger.addHandler(syslogger)
96
97
console = logging.StreamHandler()
97
console.setFormatter(logging.Formatter(u'%(name)s [%(process)d]:'
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
100
101
logger.addHandler(console)
102
103
class AvahiError(Exception):
153
154
def rename(self):
154
155
"""Derived from the Avahi example code"""
155
156
if self.rename_count >= self.max_renames:
156
logger.critical(u"No suitable Zeroconf service name found"
157
u" after %i retries, exiting.",
157
logger.critical("No suitable Zeroconf service name found"
158
" after %i retries, exiting.",
158
159
self.rename_count)
159
raise AvahiServiceError(u"Too many renames")
160
raise AvahiServiceError("Too many renames")
160
161
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
161
logger.info(u"Changing Zeroconf service name to %r ...",
162
logger.info("Changing Zeroconf service name to %r ...",
163
164
syslogger.setFormatter(logging.Formatter
164
(u'Mandos (%s) [%%(process)d]:'
165
u' %%(levelname)s: %%(message)s'
165
('Mandos (%s) [%%(process)d]:'
166
' %%(levelname)s: %%(message)s'
170
171
except dbus.exceptions.DBusException, error:
171
logger.critical(u"DBusException: %s", error)
172
logger.critical("DBusException: %s", error)
174
175
self.rename_count += 1
199
200
self.group.Commit()
200
201
def entry_group_state_changed(self, state, error):
201
202
"""Derived from the Avahi example code"""
202
logger.debug(u"Avahi entry group state change: %i", state)
203
logger.debug("Avahi entry group state change: %i", state)
204
205
if state == avahi.ENTRY_GROUP_ESTABLISHED:
205
logger.debug(u"Zeroconf service established.")
206
logger.debug("Zeroconf service established.")
206
207
elif state == avahi.ENTRY_GROUP_COLLISION:
207
logger.warning(u"Zeroconf service name collision.")
208
logger.info("Zeroconf service name collision.")
209
210
elif state == avahi.ENTRY_GROUP_FAILURE:
210
logger.critical(u"Avahi: Error in group state changed %s",
211
logger.critical("Avahi: Error in group state changed %s",
212
raise AvahiGroupError(u"State changed: %s"
213
raise AvahiGroupError("State changed: %s"
213
214
% unicode(error))
214
215
def cleanup(self):
215
216
"""Derived from the Avahi example code"""
240
241
"""A representation of a client host served by this server.
243
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
245
261
fingerprint: string (40 or 32 hexadecimal digits); used to
246
262
uniquely identify the client
247
secret: bytestring; sent verbatim (over TLS) to client
248
263
host: string; available for use by the checker command
249
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
250
267
last_enabled: datetime.datetime(); (UTC)
252
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
253
271
timeout: datetime.timedelta(); How long from last_checked_ok
254
272
until this client is disabled
255
interval: datetime.timedelta(); How often to start a new checker
256
disable_hook: If set, called by disable() as disable_hook(self)
257
checker: subprocess.Popen(); a running checker process used
258
to see if the client lives.
259
'None' if no process is running.
260
checker_initiator_tag: a gobject event source tag, or None
261
disable_initiator_tag: - '' -
262
checker_callback_tag: - '' -
263
checker_command: string; External command which is run to check if
264
client lives. %() expansions are done at
265
runtime with vars(self) as dict, so that for
266
instance %(name)s can be used in the command.
267
current_checker_command: string; current running checker_command
268
approval_delay: datetime.timedelta(); Time to wait for approval
269
_approved: bool(); 'None' if not yet approved/disapproved
270
approval_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")
274
282
def _timedelta_to_milliseconds(td):
275
283
"Convert a datetime.timedelta() to milliseconds"
296
304
if config is None:
298
logger.debug(u"Creating client %r", self.name)
306
logger.debug("Creating client %r", self.name)
299
307
# Uppercase and remove spaces from fingerprint for later
300
308
# comparison purposes with return value from the fingerprint()
302
self.fingerprint = (config[u"fingerprint"].upper()
304
logger.debug(u" Fingerprint: %s", self.fingerprint)
305
if u"secret" in config:
306
self.secret = config[u"secret"].decode(u"base64")
307
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:
308
316
with open(os.path.expanduser(os.path.expandvars
309
(config[u"secfile"])),
317
(config["secfile"])),
310
318
"rb") as secfile:
311
319
self.secret = secfile.read()
313
raise TypeError(u"No secret or secfile for client %s"
321
raise TypeError("No secret or secfile for client %s"
315
self.host = config.get(u"host", u"")
323
self.host = config.get("host", "")
316
324
self.created = datetime.datetime.utcnow()
317
325
self.enabled = False
326
self.last_approval_request = None
318
327
self.last_enabled = None
319
328
self.last_checked_ok = None
320
self.timeout = string_to_delta(config[u"timeout"])
321
self.interval = string_to_delta(config[u"interval"])
329
self.timeout = string_to_delta(config["timeout"])
330
self.interval = string_to_delta(config["interval"])
322
331
self.disable_hook = disable_hook
323
332
self.checker = None
324
333
self.checker_initiator_tag = None
325
334
self.disable_initiator_tag = None
326
335
self.checker_callback_tag = None
327
self.checker_command = config[u"checker"]
336
self.checker_command = config["checker"]
328
337
self.current_checker_command = None
329
338
self.last_connect = None
330
339
self._approved = None
331
self.approved_by_default = config.get(u"approved_by_default",
340
self.approved_by_default = config.get("approved_by_default",
333
342
self.approvals_pending = 0
334
343
self.approval_delay = string_to_delta(
335
config[u"approval_delay"])
344
config["approval_delay"])
336
345
self.approval_duration = string_to_delta(
337
config[u"approval_duration"])
346
config["approval_duration"])
338
347
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
340
349
def send_changedstate(self):
370
379
self.send_changedstate()
372
logger.info(u"Disabling client %s", self.name)
373
if getattr(self, u"disable_initiator_tag", False):
381
logger.info("Disabling client %s", self.name)
382
if getattr(self, "disable_initiator_tag", False):
374
383
gobject.source_remove(self.disable_initiator_tag)
375
384
self.disable_initiator_tag = None
376
if getattr(self, u"checker_initiator_tag", False):
385
if getattr(self, "checker_initiator_tag", False):
377
386
gobject.source_remove(self.checker_initiator_tag)
378
387
self.checker_initiator_tag = None
379
388
self.stop_checker()
450
462
command = self.checker_command % self.host
451
463
except TypeError:
452
464
# Escape attributes for the shell
453
escaped_attrs = dict((key,
454
re.escape(unicode(str(val),
458
vars(self).iteritems())
465
escaped_attrs = dict(
467
re.escape(unicode(str(getattr(self, attr, "")),
471
self.runtime_expansions)
460
474
command = self.checker_command % escaped_attrs
461
475
except TypeError, error:
462
logger.error(u'Could not format string "%s":'
463
u' %s', self.checker_command, error)
476
logger.error('Could not format string "%s":'
477
' %s', self.checker_command, error)
464
478
return True # Try again later
465
479
self.current_checker_command = command
467
logger.info(u"Starting checker %r for %s",
481
logger.info("Starting checker %r for %s",
468
482
command, self.name)
469
483
# We don't need to redirect stdout and stderr, since
470
484
# in normal mode, that is already done by daemon(),
522
536
# Encoding deeply encoded byte arrays is not supported yet by the
523
537
# "Set" method, so we fail early here:
524
if byte_arrays and signature != u"ay":
525
raise ValueError(u"Byte arrays not supported for non-'ay'"
526
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)
527
541
def decorator(func):
528
542
func._dbus_is_property = True
529
543
func._dbus_interface = dbus_interface
530
544
func._dbus_signature = signature
531
545
func._dbus_access = access
532
546
func._dbus_name = func.__name__
533
if func._dbus_name.endswith(u"_dbus_property"):
547
if func._dbus_name.endswith("_dbus_property"):
534
548
func._dbus_name = func._dbus_name[:-14]
535
func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
549
func._dbus_get_args_options = {'byte_arrays': byte_arrays }
592
606
# No such property
593
raise DBusPropertyNotFound(self.dbus_object_path + u":"
594
+ interface_name + u"."
607
raise DBusPropertyNotFound(self.dbus_object_path + ":"
608
+ interface_name + "."
597
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
611
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
599
613
def Get(self, interface_name, property_name):
600
614
"""Standard D-Bus property Get() method, see D-Bus standard.
602
616
prop = self._get_dbus_property(interface_name, property_name)
603
if prop._dbus_access == u"write":
617
if prop._dbus_access == "write":
604
618
raise DBusPropertyAccessException(property_name)
606
if not hasattr(value, u"variant_level"):
620
if not hasattr(value, "variant_level"):
608
622
return type(value)(value, variant_level=value.variant_level+1)
610
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
624
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
611
625
def Set(self, interface_name, property_name, value):
612
626
"""Standard D-Bus property Set() method, see D-Bus standard.
614
628
prop = self._get_dbus_property(interface_name, property_name)
615
if prop._dbus_access == u"read":
629
if prop._dbus_access == "read":
616
630
raise DBusPropertyAccessException(property_name)
617
if prop._dbus_get_args_options[u"byte_arrays"]:
631
if prop._dbus_get_args_options["byte_arrays"]:
618
632
# The byte_arrays option is not supported yet on
619
633
# signatures other than "ay".
620
if prop._dbus_signature != u"ay":
634
if prop._dbus_signature != "ay":
622
636
value = dbus.ByteArray(''.join(unichr(byte)
623
637
for byte in value))
626
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
627
out_signature=u"a{sv}")
640
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
641
out_signature="a{sv}")
628
642
def GetAll(self, interface_name):
629
643
"""Standard D-Bus property GetAll() method, see D-Bus
638
652
# Interface non-empty but did not match
640
654
# Ignore write-only properties
641
if prop._dbus_access == u"write":
655
if prop._dbus_access == "write":
644
if not hasattr(value, u"variant_level"):
658
if not hasattr(value, "variant_level"):
645
659
all[name] = value
647
661
all[name] = type(value)(value, variant_level=
648
662
value.variant_level+1)
649
return dbus.Dictionary(all, signature=u"sv")
663
return dbus.Dictionary(all, signature="sv")
651
665
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
653
667
path_keyword='object_path',
654
668
connection_keyword='connection')
655
669
def Introspect(self, object_path, connection):
661
675
document = xml.dom.minidom.parseString(xmlstring)
662
676
def make_tag(document, name, prop):
663
e = document.createElement(u"property")
664
e.setAttribute(u"name", name)
665
e.setAttribute(u"type", prop._dbus_signature)
666
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)
668
for if_tag in document.getElementsByTagName(u"interface"):
682
for if_tag in document.getElementsByTagName("interface"):
669
683
for tag in (make_tag(document, name, prop)
671
685
in self._get_all_dbus_properties()
672
686
if prop._dbus_interface
673
== if_tag.getAttribute(u"name")):
687
== if_tag.getAttribute("name")):
674
688
if_tag.appendChild(tag)
675
689
# Add the names to the return values for the
676
690
# "org.freedesktop.DBus.Properties" methods
677
if (if_tag.getAttribute(u"name")
678
== u"org.freedesktop.DBus.Properties"):
679
for cn in if_tag.getElementsByTagName(u"method"):
680
if cn.getAttribute(u"name") == u"Get":
681
for arg in cn.getElementsByTagName(u"arg"):
682
if (arg.getAttribute(u"direction")
684
arg.setAttribute(u"name", u"value")
685
elif cn.getAttribute(u"name") == u"GetAll":
686
for arg in cn.getElementsByTagName(u"arg"):
687
if (arg.getAttribute(u"direction")
689
arg.setAttribute(u"name", u"props")
690
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")
691
705
document.unlink()
692
706
except (AttributeError, xml.dom.DOMException,
693
707
xml.parsers.expat.ExpatError), error:
694
logger.error(u"Failed to override Introspection method",
708
logger.error("Failed to override Introspection method",
740
760
variant_level=variant_level)
742
762
def enable(self):
743
oldstate = getattr(self, u"enabled", False)
763
oldstate = getattr(self, "enabled", False)
744
764
r = Client.enable(self)
745
765
if oldstate != self.enabled:
746
766
# Emit D-Bus signals
747
self.PropertyChanged(dbus.String(u"Enabled"),
767
self.PropertyChanged(dbus.String("Enabled"),
748
768
dbus.Boolean(True, variant_level=1))
749
769
self.PropertyChanged(
750
dbus.String(u"LastEnabled"),
770
dbus.String("LastEnabled"),
751
771
self._datetime_to_dbus(self.last_enabled,
752
772
variant_level=1))
755
775
def disable(self, quiet = False):
756
oldstate = getattr(self, u"enabled", False)
776
oldstate = getattr(self, "enabled", False)
757
777
r = Client.disable(self, quiet=quiet)
758
778
if not quiet and oldstate != self.enabled:
759
779
# Emit D-Bus signal
760
self.PropertyChanged(dbus.String(u"Enabled"),
780
self.PropertyChanged(dbus.String("Enabled"),
761
781
dbus.Boolean(False, variant_level=1))
796
816
r = Client.checked_ok(self, *args, **kwargs)
797
817
# Emit D-Bus signal
798
818
self.PropertyChanged(
799
dbus.String(u"LastCheckedOK"),
819
dbus.String("LastCheckedOK"),
800
820
(self._datetime_to_dbus(self.last_checked_ok,
801
821
variant_level=1)))
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,
804
833
def start_checker(self, *args, **kwargs):
805
834
old_checker = self.checker
806
835
if self.checker is not None:
814
843
# Emit D-Bus signal
815
844
self.CheckerStarted(self.current_checker_command)
816
845
self.PropertyChanged(
817
dbus.String(u"CheckerRunning"),
846
dbus.String("CheckerRunning"),
818
847
dbus.Boolean(True, variant_level=1))
821
850
def stop_checker(self, *args, **kwargs):
822
old_checker = getattr(self, u"checker", None)
851
old_checker = getattr(self, "checker", None)
823
852
r = Client.stop_checker(self, *args, **kwargs)
824
853
if (old_checker is not None
825
and getattr(self, u"checker", None) is None):
826
self.PropertyChanged(dbus.String(u"CheckerRunning"),
854
and getattr(self, "checker", None) is None):
855
self.PropertyChanged(dbus.String("CheckerRunning"),
827
856
dbus.Boolean(False, variant_level=1))
842
871
## D-Bus methods, signals & properties
843
_interface = u"se.bsnet.fukt.Mandos.Client"
872
_interface = "se.bsnet.fukt.Mandos.Client"
847
876
# CheckerCompleted - signal
848
@dbus.service.signal(_interface, signature=u"nxs")
877
@dbus.service.signal(_interface, signature="nxs")
849
878
def CheckerCompleted(self, exitcode, waitstatus, command):
853
882
# CheckerStarted - signal
854
@dbus.service.signal(_interface, signature=u"s")
883
@dbus.service.signal(_interface, signature="s")
855
884
def CheckerStarted(self, command):
859
888
# PropertyChanged - signal
860
@dbus.service.signal(_interface, signature=u"sv")
889
@dbus.service.signal(_interface, signature="sv")
861
890
def PropertyChanged(self, property, value):
874
903
# Rejected - signal
875
@dbus.service.signal(_interface, signature=u"s")
904
@dbus.service.signal(_interface, signature="s")
876
905
def Rejected(self, reason):
880
909
# NeedApproval - signal
881
@dbus.service.signal(_interface, signature=u"tb")
910
@dbus.service.signal(_interface, signature="tb")
882
911
def NeedApproval(self, timeout, default):
913
return self.need_approval()
888
917
# Approve - method
889
@dbus.service.method(_interface, in_signature=u"b")
918
@dbus.service.method(_interface, in_signature="b")
890
919
def Approve(self, value):
891
920
self.approve(value)
893
922
# CheckedOK - method
894
923
@dbus.service.method(_interface)
895
924
def CheckedOK(self):
923
952
# ApprovalPending - property
924
@dbus_service_property(_interface, signature=u"b", access=u"read")
953
@dbus_service_property(_interface, signature="b", access="read")
925
954
def ApprovalPending_dbus_property(self):
926
955
return dbus.Boolean(bool(self.approvals_pending))
928
957
# ApprovedByDefault - property
929
@dbus_service_property(_interface, signature=u"b",
958
@dbus_service_property(_interface, signature="b",
931
960
def ApprovedByDefault_dbus_property(self, value=None):
932
961
if value is None: # get
933
962
return dbus.Boolean(self.approved_by_default)
934
963
self.approved_by_default = bool(value)
935
964
# Emit D-Bus signal
936
self.PropertyChanged(dbus.String(u"ApprovedByDefault"),
965
self.PropertyChanged(dbus.String("ApprovedByDefault"),
937
966
dbus.Boolean(value, variant_level=1))
939
968
# ApprovalDelay - property
940
@dbus_service_property(_interface, signature=u"t",
969
@dbus_service_property(_interface, signature="t",
942
971
def ApprovalDelay_dbus_property(self, value=None):
943
972
if value is None: # get
944
973
return dbus.UInt64(self.approval_delay_milliseconds())
945
974
self.approval_delay = datetime.timedelta(0, 0, 0, value)
946
975
# Emit D-Bus signal
947
self.PropertyChanged(dbus.String(u"ApprovalDelay"),
976
self.PropertyChanged(dbus.String("ApprovalDelay"),
948
977
dbus.UInt64(value, variant_level=1))
950
979
# ApprovalDuration - property
951
@dbus_service_property(_interface, signature=u"t",
980
@dbus_service_property(_interface, signature="t",
953
982
def ApprovalDuration_dbus_property(self, value=None):
954
983
if value is None: # get
955
984
return dbus.UInt64(self._timedelta_to_milliseconds(
956
985
self.approval_duration))
957
986
self.approval_duration = datetime.timedelta(0, 0, 0, value)
958
987
# Emit D-Bus signal
959
self.PropertyChanged(dbus.String(u"ApprovalDuration"),
988
self.PropertyChanged(dbus.String("ApprovalDuration"),
960
989
dbus.UInt64(value, variant_level=1))
962
991
# Name - property
963
@dbus_service_property(_interface, signature=u"s", access=u"read")
992
@dbus_service_property(_interface, signature="s", access="read")
964
993
def Name_dbus_property(self):
965
994
return dbus.String(self.name)
967
996
# Fingerprint - property
968
@dbus_service_property(_interface, signature=u"s", access=u"read")
997
@dbus_service_property(_interface, signature="s", access="read")
969
998
def Fingerprint_dbus_property(self):
970
999
return dbus.String(self.fingerprint)
972
1001
# Host - property
973
@dbus_service_property(_interface, signature=u"s",
1002
@dbus_service_property(_interface, signature="s",
975
1004
def Host_dbus_property(self, value=None):
976
1005
if value is None: # get
977
1006
return dbus.String(self.host)
978
1007
self.host = value
979
1008
# Emit D-Bus signal
980
self.PropertyChanged(dbus.String(u"Host"),
1009
self.PropertyChanged(dbus.String("Host"),
981
1010
dbus.String(value, variant_level=1))
983
1012
# Created - property
984
@dbus_service_property(_interface, signature=u"s", access=u"read")
1013
@dbus_service_property(_interface, signature="s", access="read")
985
1014
def Created_dbus_property(self):
986
1015
return dbus.String(self._datetime_to_dbus(self.created))
988
1017
# LastEnabled - property
989
@dbus_service_property(_interface, signature=u"s", access=u"read")
1018
@dbus_service_property(_interface, signature="s", access="read")
990
1019
def LastEnabled_dbus_property(self):
991
1020
if self.last_enabled is None:
992
return dbus.String(u"")
1021
return dbus.String("")
993
1022
return dbus.String(self._datetime_to_dbus(self.last_enabled))
995
1024
# Enabled - property
996
@dbus_service_property(_interface, signature=u"b",
1025
@dbus_service_property(_interface, signature="b",
998
1027
def Enabled_dbus_property(self, value=None):
999
1028
if value is None: # get
1000
1029
return dbus.Boolean(self.enabled)
1006
1035
# LastCheckedOK - property
1007
@dbus_service_property(_interface, signature=u"s",
1008
access=u"readwrite")
1036
@dbus_service_property(_interface, signature="s",
1009
1038
def LastCheckedOK_dbus_property(self, value=None):
1010
1039
if value is not None:
1011
1040
self.checked_ok()
1013
1042
if self.last_checked_ok is None:
1014
return dbus.String(u"")
1043
return dbus.String("")
1015
1044
return dbus.String(self._datetime_to_dbus(self
1016
1045
.last_checked_ok))
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))
1018
1056
# Timeout - property
1019
@dbus_service_property(_interface, signature=u"t",
1020
access=u"readwrite")
1057
@dbus_service_property(_interface, signature="t",
1021
1059
def Timeout_dbus_property(self, value=None):
1022
1060
if value is None: # get
1023
1061
return dbus.UInt64(self.timeout_milliseconds())
1024
1062
self.timeout = datetime.timedelta(0, 0, 0, value)
1025
1063
# Emit D-Bus signal
1026
self.PropertyChanged(dbus.String(u"Timeout"),
1064
self.PropertyChanged(dbus.String("Timeout"),
1027
1065
dbus.UInt64(value, variant_level=1))
1028
if getattr(self, u"disable_initiator_tag", None) is None:
1066
if getattr(self, "disable_initiator_tag", None) is None:
1030
1068
# Reschedule timeout
1031
1069
gobject.source_remove(self.disable_initiator_tag)
1044
1082
(time_to_die, self.disable))
1046
1084
# Interval - property
1047
@dbus_service_property(_interface, signature=u"t",
1048
access=u"readwrite")
1085
@dbus_service_property(_interface, signature="t",
1049
1087
def Interval_dbus_property(self, value=None):
1050
1088
if value is None: # get
1051
1089
return dbus.UInt64(self.interval_milliseconds())
1052
1090
self.interval = datetime.timedelta(0, 0, 0, value)
1053
1091
# Emit D-Bus signal
1054
self.PropertyChanged(dbus.String(u"Interval"),
1092
self.PropertyChanged(dbus.String("Interval"),
1055
1093
dbus.UInt64(value, variant_level=1))
1056
if getattr(self, u"checker_initiator_tag", None) is None:
1094
if getattr(self, "checker_initiator_tag", None) is None:
1058
1096
# Reschedule checker run
1059
1097
gobject.source_remove(self.checker_initiator_tag)
1062
1100
self.start_checker() # Start one now, too
1064
1102
# Checker - property
1065
@dbus_service_property(_interface, signature=u"s",
1066
access=u"readwrite")
1103
@dbus_service_property(_interface, signature="s",
1067
1105
def Checker_dbus_property(self, value=None):
1068
1106
if value is None: # get
1069
1107
return dbus.String(self.checker_command)
1070
1108
self.checker_command = value
1071
1109
# Emit D-Bus signal
1072
self.PropertyChanged(dbus.String(u"Checker"),
1110
self.PropertyChanged(dbus.String("Checker"),
1073
1111
dbus.String(self.checker_command,
1074
1112
variant_level=1))
1076
1114
# CheckerRunning - property
1077
@dbus_service_property(_interface, signature=u"b",
1078
access=u"readwrite")
1115
@dbus_service_property(_interface, signature="b",
1079
1117
def CheckerRunning_dbus_property(self, value=None):
1080
1118
if value is None: # get
1081
1119
return dbus.Boolean(self.checker is not None)
1147
1185
# no X.509 keys are added to it. Therefore, we can use it
1148
1186
# here despite using OpenPGP certificates.
1150
#priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1151
# u"+AES-256-CBC", u"+SHA1",
1152
# u"+COMP-NULL", u"+CTYPE-OPENPGP",
1188
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
# "+AES-256-CBC", "+SHA1",
1190
# "+COMP-NULL", "+CTYPE-OPENPGP",
1154
1192
# Use a fallback default, since this MUST be set.
1155
1193
priority = self.server.gnutls_priority
1156
1194
if priority is None:
1157
priority = u"NORMAL"
1158
1196
(gnutls.library.functions
1159
1197
.gnutls_priority_set_direct(session._c_object,
1160
1198
priority, None))
1162
1200
# Start communication using the Mandos protocol
1163
1201
# Get protocol number
1164
1202
line = self.request.makefile().readline()
1165
logger.debug(u"Protocol version: %r", line)
1203
logger.debug("Protocol version: %r", line)
1167
1205
if int(line.strip().split()[0]) > 1:
1168
1206
raise RuntimeError
1169
1207
except (ValueError, IndexError, RuntimeError), error:
1170
logger.error(u"Unknown protocol version: %s", error)
1208
logger.error("Unknown protocol version: %s", error)
1173
1211
# Start GnuTLS connection
1175
1213
session.handshake()
1176
1214
except gnutls.errors.GNUTLSError, error:
1177
logger.warning(u"Handshake failed: %s", error)
1215
logger.warning("Handshake failed: %s", error)
1178
1216
# Do not run session.bye() here: the session is not
1179
1217
# established. Just abandon the request.
1181
logger.debug(u"Handshake succeeded")
1219
logger.debug("Handshake succeeded")
1183
1221
approval_required = False
1395
1433
bind to an address or port if they were not specified."""
1396
1434
if self.interface is not None:
1397
1435
if SO_BINDTODEVICE is None:
1398
logger.error(u"SO_BINDTODEVICE does not exist;"
1399
u" cannot bind to interface %s",
1436
logger.error("SO_BINDTODEVICE does not exist;"
1437
" cannot bind to interface %s",
1400
1438
self.interface)
1403
1441
self.socket.setsockopt(socket.SOL_SOCKET,
1404
1442
SO_BINDTODEVICE,
1405
1443
str(self.interface
1407
1445
except socket.error, error:
1408
1446
if error[0] == errno.EPERM:
1409
logger.error(u"No permission to"
1410
u" bind to interface %s",
1447
logger.error("No permission to"
1448
" bind to interface %s",
1411
1449
self.interface)
1412
1450
elif error[0] == errno.ENOPROTOOPT:
1413
logger.error(u"SO_BINDTODEVICE not available;"
1414
u" cannot bind to interface %s",
1451
logger.error("SO_BINDTODEVICE not available;"
1452
" cannot bind to interface %s",
1415
1453
self.interface)
1474
1512
def handle_ipc(self, source, condition, parent_pipe=None,
1475
1513
client_object=None):
1476
1514
condition_names = {
1477
gobject.IO_IN: u"IN", # There is data to read.
1478
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
1480
gobject.IO_PRI: u"PRI", # There is urgent data to read.
1481
gobject.IO_ERR: u"ERR", # Error condition.
1482
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
1483
1521
# broken, usually for pipes and
1549
1583
def string_to_delta(interval):
1550
1584
"""Parse a string and return a datetime.timedelta
1552
>>> string_to_delta(u'7d')
1586
>>> string_to_delta('7d')
1553
1587
datetime.timedelta(7)
1554
>>> string_to_delta(u'60s')
1588
>>> string_to_delta('60s')
1555
1589
datetime.timedelta(0, 60)
1556
>>> string_to_delta(u'60m')
1590
>>> string_to_delta('60m')
1557
1591
datetime.timedelta(0, 3600)
1558
>>> string_to_delta(u'24h')
1592
>>> string_to_delta('24h')
1559
1593
datetime.timedelta(1)
1560
>>> string_to_delta(u'1w')
1594
>>> string_to_delta('1w')
1561
1595
datetime.timedelta(7)
1562
>>> string_to_delta(u'5m 30s')
1596
>>> string_to_delta('5m 30s')
1563
1597
datetime.timedelta(0, 330)
1565
1599
timevalue = datetime.timedelta(0)
1568
1602
suffix = unicode(s[-1])
1569
1603
value = int(s[:-1])
1571
1605
delta = datetime.timedelta(value)
1572
elif suffix == u"s":
1573
1607
delta = datetime.timedelta(0, value)
1574
elif suffix == u"m":
1575
1609
delta = datetime.timedelta(0, 0, 0, 0, value)
1576
elif suffix == u"h":
1577
1611
delta = datetime.timedelta(0, 0, 0, 0, 0, value)
1578
elif suffix == u"w":
1579
1613
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1581
raise ValueError(u"Unknown suffix %r" % suffix)
1615
raise ValueError("Unknown suffix %r" % suffix)
1582
1616
except (ValueError, IndexError), e:
1583
raise ValueError(e.message)
1617
raise ValueError(*(e.args))
1584
1618
timevalue += delta
1585
1619
return timevalue
1592
1626
global if_nametoindex
1594
1628
if_nametoindex = (ctypes.cdll.LoadLibrary
1595
(ctypes.util.find_library(u"c"))
1629
(ctypes.util.find_library("c"))
1596
1630
.if_nametoindex)
1597
1631
except (OSError, AttributeError):
1598
logger.warning(u"Doing if_nametoindex the hard way")
1632
logger.warning("Doing if_nametoindex the hard way")
1599
1633
def if_nametoindex(interface):
1600
1634
"Get an interface index the hard way, i.e. using fcntl()"
1601
1635
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1602
1636
with contextlib.closing(socket.socket()) as s:
1603
1637
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1604
struct.pack(str(u"16s16x"),
1638
struct.pack(str("16s16x"),
1606
interface_index = struct.unpack(str(u"I"),
1640
interface_index = struct.unpack(str("I"),
1607
1641
ifreq[16:20])[0]
1608
1642
return interface_index
1609
1643
return if_nametoindex(interface)
1639
1673
##################################################################
1640
1674
# Parsing of options, both command line and config file
1642
parser = optparse.OptionParser(version = "%%prog %s" % version)
1643
parser.add_option("-i", u"--interface", type=u"string",
1644
metavar="IF", help=u"Bind to interface IF")
1645
parser.add_option("-a", u"--address", type=u"string",
1646
help=u"Address to listen for requests on")
1647
parser.add_option("-p", u"--port", type=u"int",
1648
help=u"Port number to receive requests on")
1649
parser.add_option("--check", action=u"store_true",
1650
help=u"Run self-test")
1651
parser.add_option("--debug", action=u"store_true",
1652
help=u"Debug mode; run in foreground and log to"
1654
parser.add_option("--debuglevel", type=u"string", metavar="Level",
1655
help=u"Debug level for stdout output")
1656
parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1657
u" priority string (see GnuTLS documentation)")
1658
parser.add_option("--servicename", type=u"string",
1659
metavar=u"NAME", help=u"Zeroconf service name")
1660
parser.add_option("--configdir", type=u"string",
1661
default=u"/etc/mandos", metavar=u"DIR",
1662
help=u"Directory to search for configuration"
1664
parser.add_option("--no-dbus", action=u"store_false",
1665
dest=u"use_dbus", help=u"Do not provide D-Bus"
1666
u" system bus interface")
1667
parser.add_option("--no-ipv6", action=u"store_false",
1668
dest=u"use_ipv6", help=u"Do not use IPv6")
1669
options = parser.parse_args()[0]
1676
parser = argparse.ArgumentParser()
1677
parser.add_argument("-v", "--version", action="version",
1678
version = "%%(prog)s %s" % version,
1679
help="show version number and exit")
1680
parser.add_argument("-i", "--interface", metavar="IF",
1681
help="Bind to interface IF")
1682
parser.add_argument("-a", "--address",
1683
help="Address to listen for requests on")
1684
parser.add_argument("-p", "--port", type=int,
1685
help="Port number to receive requests on")
1686
parser.add_argument("--check", action="store_true",
1687
help="Run self-test")
1688
parser.add_argument("--debug", action="store_true",
1689
help="Debug mode; run in foreground and log"
1691
parser.add_argument("--debuglevel", metavar="LEVEL",
1692
help="Debug level for stdout output")
1693
parser.add_argument("--priority", help="GnuTLS"
1694
" priority string (see GnuTLS documentation)")
1695
parser.add_argument("--servicename",
1696
metavar="NAME", help="Zeroconf service name")
1697
parser.add_argument("--configdir",
1698
default="/etc/mandos", metavar="DIR",
1699
help="Directory to search for configuration"
1701
parser.add_argument("--no-dbus", action="store_false",
1702
dest="use_dbus", help="Do not provide D-Bus"
1703
" system bus interface")
1704
parser.add_argument("--no-ipv6", action="store_false",
1705
dest="use_ipv6", help="Do not use IPv6")
1706
options = parser.parse_args()
1671
1708
if options.check:
1676
1713
# Default values for config file for server-global settings
1677
server_defaults = { u"interface": u"",
1682
u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1683
u"servicename": u"Mandos",
1684
u"use_dbus": u"True",
1685
u"use_ipv6": u"True",
1714
server_defaults = { "interface": "",
1719
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1720
"servicename": "Mandos",
1689
1726
# Parse config file for server-global settings
1690
1727
server_config = configparser.SafeConfigParser(server_defaults)
1691
1728
del server_defaults
1692
1729
server_config.read(os.path.join(options.configdir,
1694
1731
# Convert the SafeConfigParser object to a dict
1695
1732
server_settings = server_config.defaults()
1696
1733
# Use the appropriate methods on the non-string config options
1697
for option in (u"debug", u"use_dbus", u"use_ipv6"):
1698
server_settings[option] = server_config.getboolean(u"DEFAULT",
1734
for option in ("debug", "use_dbus", "use_ipv6"):
1735
server_settings[option] = server_config.getboolean("DEFAULT",
1700
1737
if server_settings["port"]:
1701
server_settings["port"] = server_config.getint(u"DEFAULT",
1738
server_settings["port"] = server_config.getint("DEFAULT",
1703
1740
del server_config
1705
1742
# Override the settings from the config file with command line
1706
1743
# options, if set.
1707
for option in (u"interface", u"address", u"port", u"debug",
1708
u"priority", u"servicename", u"configdir",
1709
u"use_dbus", u"use_ipv6", u"debuglevel"):
1744
for option in ("interface", "address", "port", "debug",
1745
"priority", "servicename", "configdir",
1746
"use_dbus", "use_ipv6", "debuglevel"):
1710
1747
value = getattr(options, option)
1711
1748
if value is not None:
1712
1749
server_settings[option] = value
1720
1757
##################################################################
1722
1759
# For convenience
1723
debug = server_settings[u"debug"]
1724
debuglevel = server_settings[u"debuglevel"]
1725
use_dbus = server_settings[u"use_dbus"]
1726
use_ipv6 = server_settings[u"use_ipv6"]
1760
debug = server_settings["debug"]
1761
debuglevel = server_settings["debuglevel"]
1762
use_dbus = server_settings["use_dbus"]
1763
use_ipv6 = server_settings["use_ipv6"]
1728
if server_settings[u"servicename"] != u"Mandos":
1765
if server_settings["servicename"] != "Mandos":
1729
1766
syslogger.setFormatter(logging.Formatter
1730
(u'Mandos (%s) [%%(process)d]:'
1731
u' %%(levelname)s: %%(message)s'
1732
% server_settings[u"servicename"]))
1767
('Mandos (%s) [%%(process)d]:'
1768
' %%(levelname)s: %%(message)s'
1769
% server_settings["servicename"]))
1734
1771
# Parse config file with clients
1735
client_defaults = { u"timeout": u"1h",
1737
u"checker": u"fping -q -- %%(host)s",
1739
u"approval_delay": u"0s",
1740
u"approval_duration": u"1s",
1772
client_defaults = { "timeout": "1h",
1774
"checker": "fping -q -- %%(host)s",
1776
"approval_delay": "0s",
1777
"approval_duration": "1s",
1742
1779
client_config = configparser.SafeConfigParser(client_defaults)
1743
client_config.read(os.path.join(server_settings[u"configdir"],
1780
client_config.read(os.path.join(server_settings["configdir"],
1746
1783
global mandos_dbus_service
1747
1784
mandos_dbus_service = None
1749
tcp_server = MandosServer((server_settings[u"address"],
1750
server_settings[u"port"]),
1786
tcp_server = MandosServer((server_settings["address"],
1787
server_settings["port"]),
1752
interface=(server_settings[u"interface"]
1789
interface=(server_settings["interface"]
1754
1791
use_ipv6=use_ipv6,
1755
1792
gnutls_priority=
1756
server_settings[u"priority"],
1793
server_settings["priority"],
1757
1794
use_dbus=use_dbus)
1758
pidfilename = u"/var/run/mandos.pid"
1760
pidfile = open(pidfilename, u"w")
1762
logger.error(u"Could not open file %r", pidfilename)
1796
pidfilename = "/var/run/mandos.pid"
1798
pidfile = open(pidfilename, "w")
1800
logger.error("Could not open file %r", pidfilename)
1765
uid = pwd.getpwnam(u"_mandos").pw_uid
1766
gid = pwd.getpwnam(u"_mandos").pw_gid
1803
uid = pwd.getpwnam("_mandos").pw_uid
1804
gid = pwd.getpwnam("_mandos").pw_gid
1767
1805
except KeyError:
1769
uid = pwd.getpwnam(u"mandos").pw_uid
1770
gid = pwd.getpwnam(u"mandos").pw_gid
1807
uid = pwd.getpwnam("mandos").pw_uid
1808
gid = pwd.getpwnam("mandos").pw_gid
1771
1809
except KeyError:
1773
uid = pwd.getpwnam(u"nobody").pw_uid
1774
gid = pwd.getpwnam(u"nobody").pw_gid
1811
uid = pwd.getpwnam("nobody").pw_uid
1812
gid = pwd.getpwnam("nobody").pw_gid
1775
1813
except KeyError:
1822
1864
# End of Avahi example code
1825
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1867
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1826
1868
bus, do_not_queue=True)
1827
1869
except dbus.exceptions.NameExistsException, e:
1828
logger.error(unicode(e) + u", disabling D-Bus")
1870
logger.error(unicode(e) + ", disabling D-Bus")
1829
1871
use_dbus = False
1830
server_settings[u"use_dbus"] = False
1872
server_settings["use_dbus"] = False
1831
1873
tcp_server.use_dbus = False
1832
1874
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1833
service = AvahiService(name = server_settings[u"servicename"],
1834
servicetype = u"_mandos._tcp",
1875
service = AvahiService(name = server_settings["servicename"],
1876
servicetype = "_mandos._tcp",
1835
1877
protocol = protocol, bus = bus)
1836
1878
if server_settings["interface"]:
1837
1879
service.interface = (if_nametoindex
1838
(str(server_settings[u"interface"])))
1841
# Close all input and output, do double fork, etc.
1880
(str(server_settings["interface"])))
1844
1882
global multiprocessing_manager
1845
1883
multiprocessing_manager = multiprocessing.Manager()
1865
1903
client_config, section)))
1866
1904
for section in client_config.sections()))
1867
1905
if not tcp_server.clients:
1868
logger.warning(u"No clients defined")
1906
logger.warning("No clients defined")
1873
pidfile.write(str(pid) + "\n")
1876
logger.error(u"Could not write to file %r with PID %d",
1879
# "pidfile" was never created
1912
pidfile.write(str(pid) + "\n".encode("utf-8"))
1915
logger.error("Could not write to file %r with PID %d",
1918
# "pidfile" was never created
1884
1922
signal.signal(signal.SIGINT, signal.SIG_IGN)
1885
1924
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1886
1925
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1889
1928
class MandosDBusService(dbus.service.Object):
1890
1929
"""A D-Bus proxy object"""
1891
1930
def __init__(self):
1892
dbus.service.Object.__init__(self, bus, u"/")
1893
_interface = u"se.bsnet.fukt.Mandos"
1931
dbus.service.Object.__init__(self, bus, "/")
1932
_interface = "se.bsnet.fukt.Mandos"
1895
@dbus.service.signal(_interface, signature=u"o")
1934
@dbus.service.signal(_interface, signature="o")
1896
1935
def ClientAdded(self, objpath):
1900
@dbus.service.signal(_interface, signature=u"ss")
1939
@dbus.service.signal(_interface, signature="ss")
1901
1940
def ClientNotFound(self, fingerprint, address):
1905
@dbus.service.signal(_interface, signature=u"os")
1944
@dbus.service.signal(_interface, signature="os")
1906
1945
def ClientRemoved(self, objpath, name):
1910
@dbus.service.method(_interface, out_signature=u"ao")
1949
@dbus.service.method(_interface, out_signature="ao")
1911
1950
def GetAllClients(self):
1913
1952
return dbus.Array(c.dbus_object_path
1914
1953
for c in tcp_server.clients)
1916
1955
@dbus.service.method(_interface,
1917
out_signature=u"a{oa{sv}}")
1956
out_signature="a{oa{sv}}")
1918
1957
def GetAllClientsWithProperties(self):
1920
1959
return dbus.Dictionary(
1921
((c.dbus_object_path, c.GetAll(u""))
1960
((c.dbus_object_path, c.GetAll(""))
1922
1961
for c in tcp_server.clients),
1923
signature=u"oa{sv}")
1925
@dbus.service.method(_interface, in_signature=u"o")
1964
@dbus.service.method(_interface, in_signature="o")
1926
1965
def RemoveClient(self, object_path):
1928
1967
for c in tcp_server.clients:
1994
2033
(tcp_server.handle_request
1995
2034
(*args[2:], **kwargs) or True))
1997
logger.debug(u"Starting main loop")
2036
logger.debug("Starting main loop")
1998
2037
main_loop.run()
1999
2038
except AvahiError, error:
2000
logger.critical(u"AvahiError: %s", error)
2039
logger.critical("AvahiError: %s", error)
2003
2042
except KeyboardInterrupt:
2006
logger.debug(u"Server received KeyboardInterrupt")
2007
logger.debug(u"Server exiting")
2044
print("", file=sys.stderr)
2045
logger.debug("Server received KeyboardInterrupt")
2046
logger.debug("Server exiting")
2008
2047
# Must run before the D-Bus bus name gets deregistered