154
152
def rename(self):
155
153
"""Derived from the Avahi example code"""
156
154
if self.rename_count >= self.max_renames:
157
logger.critical("No suitable Zeroconf service name found"
158
" after %i retries, exiting.",
155
logger.critical(u"No suitable Zeroconf service name found"
156
u" after %i retries, exiting.",
159
157
self.rename_count)
160
raise AvahiServiceError("Too many renames")
161
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
162
logger.info("Changing Zeroconf service name to %r ...",
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 ...",
164
162
syslogger.setFormatter(logging.Formatter
165
('Mandos (%s) [%%(process)d]:'
166
' %%(levelname)s: %%(message)s'
163
(u'Mandos (%s) [%%(process)d]:'
164
u' %%(levelname)s: %%(message)s'
171
except dbus.exceptions.DBusException, error:
172
logger.critical("DBusException: %s", error)
175
168
self.rename_count += 1
176
169
def remove(self):
177
170
"""Derived from the Avahi example code"""
241
234
"""A representation of a client host served by this server.
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
237
name: string; from the config file, used in log messages and
239
fingerprint: string (40 or 32 hexadecimal digits); used to
240
uniquely identify the client
241
secret: bytestring; sent verbatim (over TLS) to client
242
host: string; available for use by the checker command
243
created: datetime.datetime(); (UTC) object creation
244
last_enabled: datetime.datetime(); (UTC)
246
last_checked_ok: datetime.datetime(); (UTC) or None
247
timeout: datetime.timedelta(); How long from last_checked_ok
248
until this client is disabled
249
interval: datetime.timedelta(); How often to start a new checker
250
disable_hook: If set, called by disable() as disable_hook(self)
247
251
checker: subprocess.Popen(); a running checker process used
248
252
to see if the client lives.
249
253
'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
254
checker_initiator_tag: a gobject event source tag, or None
255
disable_initiator_tag: - '' -
256
checker_callback_tag: - '' -
257
checker_command: string; External command which is run to check if
258
client lives. %() expansions are done at
253
259
runtime with vars(self) as dict, so that for
254
260
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
261
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
261
fingerprint: string (40 or 32 hexadecimal digits); used to
262
uniquely identify the client
263
host: string; available for use by the checker command
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
267
last_enabled: datetime.datetime(); (UTC)
268
name: string; from the config file, used in log messages and
270
secret: bytestring; sent verbatim (over TLS) to client
271
timeout: datetime.timedelta(); How long from last_checked_ok
272
until this client is disabled
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")
282
265
def _timedelta_to_milliseconds(td):
283
266
"Convert a datetime.timedelta() to milliseconds"
304
284
if config is None:
306
logger.debug("Creating client %r", self.name)
286
logger.debug(u"Creating client %r", self.name)
307
287
# Uppercase and remove spaces from fingerprint for later
308
288
# comparison purposes with return value from the fingerprint()
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:
290
self.fingerprint = (config[u"fingerprint"].upper()
292
logger.debug(u" Fingerprint: %s", self.fingerprint)
293
if u"secret" in config:
294
self.secret = config[u"secret"].decode(u"base64")
295
elif u"secfile" in config:
316
296
with open(os.path.expanduser(os.path.expandvars
317
(config["secfile"])),
297
(config[u"secfile"])),
318
298
"rb") as secfile:
319
299
self.secret = secfile.read()
321
raise TypeError("No secret or secfile for client %s"
301
raise TypeError(u"No secret or secfile for client %s"
323
self.host = config.get("host", "")
303
self.host = config.get(u"host", u"")
324
304
self.created = datetime.datetime.utcnow()
325
305
self.enabled = False
326
self.last_approval_request = None
327
306
self.last_enabled = None
328
307
self.last_checked_ok = None
329
self.timeout = string_to_delta(config["timeout"])
330
self.interval = string_to_delta(config["interval"])
308
self.timeout = string_to_delta(config[u"timeout"])
309
self.interval = string_to_delta(config[u"interval"])
331
310
self.disable_hook = disable_hook
332
311
self.checker = None
333
312
self.checker_initiator_tag = None
334
313
self.disable_initiator_tag = None
335
314
self.checker_callback_tag = None
336
self.checker_command = config["checker"]
315
self.checker_command = config[u"checker"]
337
316
self.current_checker_command = None
338
317
self.last_connect = None
339
self._approved = None
340
self.approved_by_default = config.get("approved_by_default",
342
self.approvals_pending = 0
343
self.approval_delay = string_to_delta(
344
config["approval_delay"])
345
self.approval_duration = string_to_delta(
346
config["approval_duration"])
347
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
349
def send_changedstate(self):
350
self.changedstate.acquire()
351
self.changedstate.notify_all()
352
self.changedstate.release()
354
319
def enable(self):
355
320
"""Start this client's checker and timeout hooks"""
356
if getattr(self, "enabled", False):
321
if getattr(self, u"enabled", False):
357
322
# Already enabled
359
self.send_changedstate()
360
324
self.last_enabled = datetime.datetime.utcnow()
361
325
# Schedule a new checker to be started an 'interval' from now,
362
326
# and every interval from then on.
606
564
# No such property
607
raise DBusPropertyNotFound(self.dbus_object_path + ":"
608
+ interface_name + "."
565
raise DBusPropertyNotFound(self.dbus_object_path + u":"
566
+ interface_name + u"."
611
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
569
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
613
571
def Get(self, interface_name, property_name):
614
572
"""Standard D-Bus property Get() method, see D-Bus standard.
616
574
prop = self._get_dbus_property(interface_name, property_name)
617
if prop._dbus_access == "write":
575
if prop._dbus_access == u"write":
618
576
raise DBusPropertyAccessException(property_name)
620
if not hasattr(value, "variant_level"):
578
if not hasattr(value, u"variant_level"):
622
580
return type(value)(value, variant_level=value.variant_level+1)
624
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
582
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
625
583
def Set(self, interface_name, property_name, value):
626
584
"""Standard D-Bus property Set() method, see D-Bus standard.
628
586
prop = self._get_dbus_property(interface_name, property_name)
629
if prop._dbus_access == "read":
587
if prop._dbus_access == u"read":
630
588
raise DBusPropertyAccessException(property_name)
631
if prop._dbus_get_args_options["byte_arrays"]:
589
if prop._dbus_get_args_options[u"byte_arrays"]:
632
590
# The byte_arrays option is not supported yet on
633
591
# signatures other than "ay".
634
if prop._dbus_signature != "ay":
592
if prop._dbus_signature != u"ay":
636
594
value = dbus.ByteArray(''.join(unichr(byte)
637
595
for byte in value))
640
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
641
out_signature="a{sv}")
598
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
599
out_signature=u"a{sv}")
642
600
def GetAll(self, interface_name):
643
601
"""Standard D-Bus property GetAll() method, see D-Bus
675
633
document = xml.dom.minidom.parseString(xmlstring)
676
634
def make_tag(document, name, prop):
677
e = document.createElement("property")
678
e.setAttribute("name", name)
679
e.setAttribute("type", prop._dbus_signature)
680
e.setAttribute("access", prop._dbus_access)
635
e = document.createElement(u"property")
636
e.setAttribute(u"name", name)
637
e.setAttribute(u"type", prop._dbus_signature)
638
e.setAttribute(u"access", prop._dbus_access)
682
for if_tag in document.getElementsByTagName("interface"):
640
for if_tag in document.getElementsByTagName(u"interface"):
683
641
for tag in (make_tag(document, name, prop)
685
643
in self._get_all_dbus_properties()
686
644
if prop._dbus_interface
687
== if_tag.getAttribute("name")):
645
== if_tag.getAttribute(u"name")):
688
646
if_tag.appendChild(tag)
689
647
# Add the names to the return values for the
690
648
# "org.freedesktop.DBus.Properties" methods
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")
649
if (if_tag.getAttribute(u"name")
650
== u"org.freedesktop.DBus.Properties"):
651
for cn in if_tag.getElementsByTagName(u"method"):
652
if cn.getAttribute(u"name") == u"Get":
653
for arg in cn.getElementsByTagName(u"arg"):
654
if (arg.getAttribute(u"direction")
656
arg.setAttribute(u"name", u"value")
657
elif cn.getAttribute(u"name") == u"GetAll":
658
for arg in cn.getElementsByTagName(u"arg"):
659
if (arg.getAttribute(u"direction")
661
arg.setAttribute(u"name", u"props")
662
xmlstring = document.toxml(u"utf-8")
705
663
document.unlink()
706
664
except (AttributeError, xml.dom.DOMException,
707
665
xml.parsers.expat.ExpatError), error:
708
logger.error("Failed to override Introspection method",
666
logger.error(u"Failed to override Introspection method",
717
675
dbus_object_path: dbus.ObjectPath
718
676
bus: dbus.SystemBus()
721
runtime_expansions = (Client.runtime_expansions
722
+ ("dbus_object_path",))
724
678
# dbus.service.Object doesn't use super(), so we can't either.
726
680
def __init__(self, bus = None, *args, **kwargs):
727
self._approvals_pending = 0
729
682
Client.__init__(self, *args, **kwargs)
730
683
# Only now, when this client is initialized, can it show up on
732
client_object_name = unicode(self.name).translate(
735
685
self.dbus_object_path = (dbus.ObjectPath
736
("/clients/" + client_object_name))
687
+ self.name.replace(u".", u"_")))
737
688
DBusObjectWithProperties.__init__(self, self.bus,
738
689
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
692
def _datetime_to_dbus(dt, variant_level=0):
760
695
variant_level=variant_level)
762
697
def enable(self):
763
oldstate = getattr(self, "enabled", False)
698
oldstate = getattr(self, u"enabled", False)
764
699
r = Client.enable(self)
765
700
if oldstate != self.enabled:
766
701
# Emit D-Bus signals
767
self.PropertyChanged(dbus.String("Enabled"),
702
self.PropertyChanged(dbus.String(u"enabled"),
768
703
dbus.Boolean(True, variant_level=1))
769
704
self.PropertyChanged(
770
dbus.String("LastEnabled"),
705
dbus.String(u"last_enabled"),
771
706
self._datetime_to_dbus(self.last_enabled,
772
707
variant_level=1))
775
710
def disable(self, quiet = False):
776
oldstate = getattr(self, "enabled", False)
711
oldstate = getattr(self, u"enabled", False)
777
712
r = Client.disable(self, quiet=quiet)
778
713
if not quiet and oldstate != self.enabled:
779
714
# Emit D-Bus signal
780
self.PropertyChanged(dbus.String("Enabled"),
715
self.PropertyChanged(dbus.String(u"enabled"),
781
716
dbus.Boolean(False, variant_level=1))
843
769
# Emit D-Bus signal
844
770
self.CheckerStarted(self.current_checker_command)
845
771
self.PropertyChanged(
846
dbus.String("CheckerRunning"),
772
dbus.String(u"checker_running"),
847
773
dbus.Boolean(True, variant_level=1))
850
776
def stop_checker(self, *args, **kwargs):
851
old_checker = getattr(self, "checker", None)
777
old_checker = getattr(self, u"checker", None)
852
778
r = Client.stop_checker(self, *args, **kwargs)
853
779
if (old_checker is not None
854
and getattr(self, "checker", None) is None):
855
self.PropertyChanged(dbus.String("CheckerRunning"),
780
and getattr(self, u"checker", None) is None):
781
self.PropertyChanged(dbus.String(u"checker_running"),
856
782
dbus.Boolean(False, variant_level=1))
859
def _reset_approved(self):
860
self._approved = None
863
def approve(self, value=True):
864
self.send_changedstate()
865
self._approved = value
866
gobject.timeout_add(self._timedelta_to_milliseconds
867
(self.approval_duration),
868
self._reset_approved)
871
785
## D-Bus methods, signals & properties
872
_interface = "se.bsnet.fukt.Mandos.Client"
786
_interface = u"se.bsnet.fukt.Mandos.Client"
876
790
# CheckerCompleted - signal
877
@dbus.service.signal(_interface, signature="nxs")
791
@dbus.service.signal(_interface, signature=u"nxs")
878
792
def CheckerCompleted(self, exitcode, waitstatus, command):
882
796
# CheckerStarted - signal
883
@dbus.service.signal(_interface, signature="s")
797
@dbus.service.signal(_interface, signature=u"s")
884
798
def CheckerStarted(self, command):
888
802
# PropertyChanged - signal
889
@dbus.service.signal(_interface, signature="sv")
803
@dbus.service.signal(_interface, signature=u"sv")
890
804
def PropertyChanged(self, property, value):
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):
853
@dbus_service_property(_interface, signature=u"s", access=u"read")
854
def name_dbus_property(self):
994
855
return dbus.String(self.name)
996
# Fingerprint - property
997
@dbus_service_property(_interface, signature="s", access="read")
998
def Fingerprint_dbus_property(self):
857
# fingerprint - property
858
@dbus_service_property(_interface, signature=u"s", access=u"read")
859
def fingerprint_dbus_property(self):
999
860
return dbus.String(self.fingerprint)
1002
@dbus_service_property(_interface, signature="s",
1004
def Host_dbus_property(self, value=None):
863
@dbus_service_property(_interface, signature=u"s",
865
def host_dbus_property(self, value=None):
1005
866
if value is None: # get
1006
867
return dbus.String(self.host)
1007
868
self.host = value
1008
869
# Emit D-Bus signal
1009
self.PropertyChanged(dbus.String("Host"),
870
self.PropertyChanged(dbus.String(u"host"),
1010
871
dbus.String(value, variant_level=1))
1012
# Created - property
1013
@dbus_service_property(_interface, signature="s", access="read")
1014
def Created_dbus_property(self):
874
@dbus_service_property(_interface, signature=u"s", access=u"read")
875
def created_dbus_property(self):
1015
876
return dbus.String(self._datetime_to_dbus(self.created))
1017
# LastEnabled - property
1018
@dbus_service_property(_interface, signature="s", access="read")
1019
def LastEnabled_dbus_property(self):
878
# last_enabled - property
879
@dbus_service_property(_interface, signature=u"s", access=u"read")
880
def last_enabled_dbus_property(self):
1020
881
if self.last_enabled is None:
1021
return dbus.String("")
882
return dbus.String(u"")
1022
883
return dbus.String(self._datetime_to_dbus(self.last_enabled))
1024
# Enabled - property
1025
@dbus_service_property(_interface, signature="b",
1027
def Enabled_dbus_property(self, value=None):
886
@dbus_service_property(_interface, signature=u"b",
888
def enabled_dbus_property(self, value=None):
1028
889
if value is None: # get
1029
890
return dbus.Boolean(self.enabled)
1035
# LastCheckedOK - property
1036
@dbus_service_property(_interface, signature="s",
1038
def LastCheckedOK_dbus_property(self, value=None):
896
# last_checked_ok - property
897
@dbus_service_property(_interface, signature=u"s",
899
def last_checked_ok_dbus_property(self, value=None):
1039
900
if value is not None:
1040
901
self.checked_ok()
1042
903
if self.last_checked_ok is None:
1043
return dbus.String("")
904
return dbus.String(u"")
1044
905
return dbus.String(self._datetime_to_dbus(self
1045
906
.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))
1056
# Timeout - property
1057
@dbus_service_property(_interface, signature="t",
1059
def Timeout_dbus_property(self, value=None):
909
@dbus_service_property(_interface, signature=u"t",
911
def timeout_dbus_property(self, value=None):
1060
912
if value is None: # get
1061
913
return dbus.UInt64(self.timeout_milliseconds())
1062
914
self.timeout = datetime.timedelta(0, 0, 0, value)
1063
915
# Emit D-Bus signal
1064
self.PropertyChanged(dbus.String("Timeout"),
916
self.PropertyChanged(dbus.String(u"timeout"),
1065
917
dbus.UInt64(value, variant_level=1))
1066
if getattr(self, "disable_initiator_tag", None) is None:
918
if getattr(self, u"disable_initiator_tag", None) is None:
1068
920
# Reschedule timeout
1069
921
gobject.source_remove(self.disable_initiator_tag)
1099
951
(value, self.start_checker))
1100
952
self.start_checker() # Start one now, too
1102
# Checker - property
1103
@dbus_service_property(_interface, signature="s",
1105
def Checker_dbus_property(self, value=None):
955
@dbus_service_property(_interface, signature=u"s",
957
def checker_dbus_property(self, value=None):
1106
958
if value is None: # get
1107
959
return dbus.String(self.checker_command)
1108
960
self.checker_command = value
1109
961
# Emit D-Bus signal
1110
self.PropertyChanged(dbus.String("Checker"),
962
self.PropertyChanged(dbus.String(u"checker"),
1111
963
dbus.String(self.checker_command,
1112
964
variant_level=1))
1114
# CheckerRunning - property
1115
@dbus_service_property(_interface, signature="b",
1117
def CheckerRunning_dbus_property(self, value=None):
966
# checker_running - property
967
@dbus_service_property(_interface, signature=u"b",
969
def checker_running_dbus_property(self, value=None):
1118
970
if value is None: # get
1119
971
return dbus.Boolean(self.checker is not None)
1123
975
self.stop_checker()
1125
# ObjectPath - property
1126
@dbus_service_property(_interface, signature="o", access="read")
1127
def ObjectPath_dbus_property(self):
977
# object_path - property
978
@dbus_service_property(_interface, signature=u"o", access=u"read")
979
def object_path_dbus_property(self):
1128
980
return self.dbus_object_path # is already a dbus.ObjectPath
1131
@dbus_service_property(_interface, signature="ay",
1132
access="write", byte_arrays=True)
1133
def Secret_dbus_property(self, value):
983
@dbus_service_property(_interface, signature=u"ay",
984
access=u"write", byte_arrays=True)
985
def secret_dbus_property(self, value):
1134
986
self.secret = str(value)
1139
class ProxyClient(object):
1140
def __init__(self, child_pipe, fpr, address):
1141
self._pipe = child_pipe
1142
self._pipe.send(('init', fpr, address))
1143
if not self._pipe.recv():
1146
def __getattribute__(self, name):
1147
if(name == '_pipe'):
1148
return super(ProxyClient, self).__getattribute__(name)
1149
self._pipe.send(('getattr', name))
1150
data = self._pipe.recv()
1151
if data[0] == 'data':
1153
if data[0] == 'function':
1154
def func(*args, **kwargs):
1155
self._pipe.send(('funcall', name, args, kwargs))
1156
return self._pipe.recv()[1]
1159
def __setattr__(self, name, value):
1160
if(name == '_pipe'):
1161
return super(ProxyClient, self).__setattr__(name, value)
1162
self._pipe.send(('setattr', name, value))
1165
991
class ClientHandler(socketserver.BaseRequestHandler, object):
1166
992
"""A class to handle client connections.
1169
995
Note: This will run in its own forked process."""
1171
997
def handle(self):
1172
with contextlib.closing(self.server.child_pipe) as child_pipe:
1173
logger.info("TCP connection from: %s",
1174
unicode(self.client_address))
1175
logger.debug("Pipe FD: %d",
1176
self.server.child_pipe.fileno())
998
logger.info(u"TCP connection from: %s",
999
unicode(self.client_address))
1000
logger.debug(u"IPC Pipe FD: %d",
1001
self.server.child_pipe[1].fileno())
1002
# Open IPC pipe to parent process
1003
with contextlib.nested(self.server.child_pipe[1],
1004
self.server.parent_pipe[0]
1005
) as (ipc, ipc_return):
1178
1006
session = (gnutls.connection
1179
1007
.ClientSession(self.request,
1180
1008
gnutls.connection
1181
1009
.X509Credentials()))
1183
1011
# Note: gnutls.connection.X509Credentials is really a
1184
1012
# generic GnuTLS certificate credentials object so long as
1185
1013
# no X.509 keys are added to it. Therefore, we can use it
1186
1014
# here despite using OpenPGP certificates.
1188
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
# "+AES-256-CBC", "+SHA1",
1190
# "+COMP-NULL", "+CTYPE-OPENPGP",
1016
#priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1017
# u"+AES-256-CBC", u"+SHA1",
1018
# u"+COMP-NULL", u"+CTYPE-OPENPGP",
1192
1020
# Use a fallback default, since this MUST be set.
1193
1021
priority = self.server.gnutls_priority
1194
1022
if priority is None:
1023
priority = u"NORMAL"
1196
1024
(gnutls.library.functions
1197
1025
.gnutls_priority_set_direct(session._c_object,
1198
1026
priority, None))
1200
1028
# Start communication using the Mandos protocol
1201
1029
# Get protocol number
1202
1030
line = self.request.makefile().readline()
1203
logger.debug("Protocol version: %r", line)
1031
logger.debug(u"Protocol version: %r", line)
1205
1033
if int(line.strip().split()[0]) > 1:
1206
1034
raise RuntimeError
1207
1035
except (ValueError, IndexError, RuntimeError), error:
1208
logger.error("Unknown protocol version: %s", error)
1036
logger.error(u"Unknown protocol version: %s", error)
1211
1039
# Start GnuTLS connection
1213
1041
session.handshake()
1214
1042
except gnutls.errors.GNUTLSError, error:
1215
logger.warning("Handshake failed: %s", error)
1043
logger.warning(u"Handshake failed: %s", error)
1216
1044
# Do not run session.bye() here: the session is not
1217
1045
# established. Just abandon the request.
1219
logger.debug("Handshake succeeded")
1221
approval_required = False
1047
logger.debug(u"Handshake succeeded")
1224
1050
fpr = self.fingerprint(self.peer_certificate
1226
1052
except (TypeError, gnutls.errors.GNUTLSError), error:
1227
logger.warning("Bad certificate: %s", error)
1053
logger.warning(u"Bad certificate: %s", error)
1229
logger.debug("Fingerprint: %s", fpr)
1055
logger.debug(u"Fingerprint: %s", fpr)
1232
client = ProxyClient(child_pipe, fpr,
1233
self.client_address)
1237
if client.approval_delay:
1238
delay = client.approval_delay
1239
client.approvals_pending += 1
1240
approval_required = True
1243
if not client.enabled:
1244
logger.warning("Client %s is disabled",
1246
if self.server.use_dbus:
1248
client.Rejected("Disabled")
1251
if client._approved or not client.approval_delay:
1252
#We are approved or approval is disabled
1057
for c in self.server.clients:
1058
if c.fingerprint == fpr:
1254
elif client._approved is None:
1255
logger.info("Client %s needs approval",
1257
if self.server.use_dbus:
1259
client.NeedApproval(
1260
client.approval_delay_milliseconds(),
1261
client.approved_by_default)
1263
logger.warning("Client %s was not approved",
1265
if self.server.use_dbus:
1267
client.Rejected("Denied")
1270
#wait until timeout or approved
1271
#x = float(client._timedelta_to_milliseconds(delay))
1272
time = datetime.datetime.now()
1273
client.changedstate.acquire()
1274
client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1275
client.changedstate.release()
1276
time2 = datetime.datetime.now()
1277
if (time2 - time) >= delay:
1278
if not client.approved_by_default:
1279
logger.warning("Client %s timed out while"
1280
" waiting for approval",
1282
if self.server.use_dbus:
1284
client.Rejected("Approval timed out")
1289
delay -= time2 - time
1062
ipc.write(u"NOTFOUND %s %s\n"
1063
% (fpr, unicode(self.client_address)))
1066
class ClientProxy(object):
1067
"""Client proxy object. Not for calling methods."""
1068
def __init__(self, client):
1069
self.client = client
1070
def __getattr__(self, name):
1071
if name.startswith("ipc_"):
1073
ipc.write("%s %s\n" % (name[4:].upper(),
1076
if not hasattr(self.client, name):
1077
raise AttributeError
1078
ipc.write(u"GETATTR %s %s\n"
1079
% (name, self.client.fingerprint))
1080
return pickle.load(ipc_return)
1081
clientproxy = ClientProxy(client)
1082
# Have to check if client.enabled, since it is
1083
# possible that the client was disabled since the
1084
# GnuTLS session was established.
1085
if not clientproxy.enabled:
1086
clientproxy.ipc_disabled()
1089
clientproxy.ipc_sending()
1292
1091
while sent_size < len(client.secret):
1294
sent = session.send(client.secret[sent_size:])
1295
except (gnutls.errors.GNUTLSError), error:
1296
logger.warning("gnutls send failed")
1298
logger.debug("Sent: %d, remaining: %d",
1092
sent = session.send(client.secret[sent_size:])
1093
logger.debug(u"Sent: %d, remaining: %d",
1299
1094
sent, len(client.secret)
1300
1095
- (sent_size + sent))
1301
1096
sent_size += sent
1303
logger.info("Sending secret to %s", client.name)
1304
# bump the timeout as if seen
1306
if self.server.use_dbus:
1311
if approval_required:
1312
client.approvals_pending -= 1
1315
except (gnutls.errors.GNUTLSError), error:
1316
logger.warning("GnuTLS bye failed")
1319
1101
def peer_certificate(session):
1375
1157
# Convert the buffer to a Python bytestring
1376
1158
fpr = ctypes.string_at(buf, buf_len.value)
1377
1159
# Convert the bytestring to hexadecimal notation
1378
hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1160
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
1382
class MultiprocessingMixIn(object):
1383
"""Like socketserver.ThreadingMixIn, but with multiprocessing"""
1384
def sub_process_main(self, request, address):
1386
self.finish_request(request, address)
1388
self.handle_error(request, address)
1389
self.close_request(request)
1391
def process_request(self, request, address):
1392
"""Start a new process to process the request."""
1393
multiprocessing.Process(target = self.sub_process_main,
1394
args = (request, address)).start()
1396
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1397
""" adds a pipe to the MixIn """
1164
class ForkingMixInWithPipes(socketserver.ForkingMixIn, object):
1165
"""Like socketserver.ForkingMixIn, but also pass a pipe pair."""
1398
1166
def process_request(self, request, client_address):
1399
1167
"""Overrides and wraps the original process_request().
1401
1169
This function creates a new pipe in self.pipe
1403
parent_pipe, self.child_pipe = multiprocessing.Pipe()
1405
super(MultiprocessingMixInWithPipe,
1171
# Child writes to child_pipe
1172
self.child_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1173
# Parent writes to parent_pipe
1174
self.parent_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1175
super(ForkingMixInWithPipes,
1406
1176
self).process_request(request, client_address)
1407
self.child_pipe.close()
1408
self.add_pipe(parent_pipe)
1410
def add_pipe(self, parent_pipe):
1177
# Close unused ends for parent
1178
self.parent_pipe[0].close() # close read end
1179
self.child_pipe[1].close() # close write end
1180
self.add_pipe_fds(self.child_pipe[0], self.parent_pipe[1])
1181
def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1411
1182
"""Dummy function; override as necessary"""
1412
raise NotImplementedError
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1183
child_pipe_fd.close()
1184
parent_pipe_fd.close()
1187
class IPv6_TCPServer(ForkingMixInWithPipes,
1415
1188
socketserver.TCPServer, object):
1416
1189
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
1502
1275
return socketserver.TCPServer.server_activate(self)
1503
1276
def enable(self):
1504
1277
self.enabled = True
1505
def add_pipe(self, parent_pipe):
1278
def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1506
1279
# Call "handle_ipc" for both data and EOF events
1507
gobject.io_add_watch(parent_pipe.fileno(),
1280
gobject.io_add_watch(child_pipe_fd.fileno(),
1508
1281
gobject.IO_IN | gobject.IO_HUP,
1509
1282
functools.partial(self.handle_ipc,
1510
parent_pipe = parent_pipe))
1512
def handle_ipc(self, source, condition, parent_pipe=None,
1513
client_object=None):
1283
reply = parent_pipe_fd,
1284
sender= child_pipe_fd))
1285
def handle_ipc(self, source, condition, reply=None, sender=None):
1514
1286
condition_names = {
1515
gobject.IO_IN: "IN", # There is data to read.
1516
gobject.IO_OUT: "OUT", # Data can be written (without
1287
gobject.IO_IN: u"IN", # There is data to read.
1288
gobject.IO_OUT: u"OUT", # Data can be written (without
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
1290
gobject.IO_PRI: u"PRI", # There is urgent data to read.
1291
gobject.IO_ERR: u"ERR", # Error condition.
1292
gobject.IO_HUP: u"HUP" # Hung up (the connection has been
1521
1293
# broken, usually for pipes and
1525
1297
for cond, name in
1526
1298
condition_names.iteritems()
1527
1299
if cond & condition)
1528
# error or the other end of multiprocessing.Pipe has closed
1529
if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1532
# Read a request from the child
1533
request = parent_pipe.recv()
1534
command = request[0]
1536
if command == 'init':
1538
address = request[2]
1540
for c in self.clients:
1541
if c.fingerprint == fpr:
1545
logger.warning("Client not found for fingerprint: %s, ad"
1546
"dress: %s", fpr, address)
1549
mandos_dbus_service.ClientNotFound(fpr, address[0])
1550
parent_pipe.send(False)
1553
gobject.io_add_watch(parent_pipe.fileno(),
1554
gobject.IO_IN | gobject.IO_HUP,
1555
functools.partial(self.handle_ipc,
1556
parent_pipe = parent_pipe,
1557
client_object = client))
1558
parent_pipe.send(True)
1559
# remove the old hook in favor of the new above hook on same fileno
1561
if command == 'funcall':
1562
funcname = request[1]
1566
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1568
if command == 'getattr':
1569
attrname = request[1]
1570
if callable(client_object.__getattribute__(attrname)):
1571
parent_pipe.send(('function',))
1573
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1575
if command == 'setattr':
1576
attrname = request[1]
1578
setattr(client_object, attrname, value)
1300
logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1303
# Read a line from the file object
1304
cmdline = sender.readline()
1305
if not cmdline: # Empty line means end of file
1306
# close the IPC pipes
1310
# Stop calling this function
1313
logger.debug(u"IPC command: %r", cmdline)
1315
# Parse and act on command
1316
cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1318
if cmd == u"NOTFOUND":
1319
fpr, address = args.split(None, 1)
1320
logger.warning(u"Client not found for fingerprint: %s, ad"
1321
u"dress: %s", fpr, address)
1324
mandos_dbus_service.ClientNotFound(fpr, address)
1325
elif cmd == u"DISABLED":
1326
for client in self.clients:
1327
if client.name == args:
1328
logger.warning(u"Client %s is disabled", args)
1334
logger.error(u"Unknown client %s is disabled", args)
1335
elif cmd == u"SENDING":
1336
for client in self.clients:
1337
if client.name == args:
1338
logger.info(u"Sending secret to %s", client.name)
1345
logger.error(u"Sending secret to unknown client %s",
1347
elif cmd == u"GETATTR":
1348
attr_name, fpr = args.split(None, 1)
1349
for client in self.clients:
1350
if client.fingerprint == fpr:
1351
attr_value = getattr(client, attr_name, None)
1352
logger.debug("IPC reply: %r", attr_value)
1353
pickle.dump(attr_value, reply)
1356
logger.error(u"Client %s on address %s requesting "
1357
u"attribute %s not found", fpr, address,
1359
pickle.dump(None, reply)
1361
logger.error(u"Unknown IPC command: %r", cmdline)
1363
# Keep calling this function
1583
1367
def string_to_delta(interval):
1584
1368
"""Parse a string and return a datetime.timedelta
1586
>>> string_to_delta('7d')
1370
>>> string_to_delta(u'7d')
1587
1371
datetime.timedelta(7)
1588
>>> string_to_delta('60s')
1372
>>> string_to_delta(u'60s')
1589
1373
datetime.timedelta(0, 60)
1590
>>> string_to_delta('60m')
1374
>>> string_to_delta(u'60m')
1591
1375
datetime.timedelta(0, 3600)
1592
>>> string_to_delta('24h')
1376
>>> string_to_delta(u'24h')
1593
1377
datetime.timedelta(1)
1594
>>> string_to_delta('1w')
1378
>>> string_to_delta(u'1w')
1595
1379
datetime.timedelta(7)
1596
>>> string_to_delta('5m 30s')
1380
>>> string_to_delta(u'5m 30s')
1597
1381
datetime.timedelta(0, 330)
1599
1383
timevalue = datetime.timedelta(0)
1673
1457
##################################################################
1674
1458
# Parsing of options, both command line and config file
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()
1460
parser = optparse.OptionParser(version = "%%prog %s" % version)
1461
parser.add_option("-i", u"--interface", type=u"string",
1462
metavar="IF", help=u"Bind to interface IF")
1463
parser.add_option("-a", u"--address", type=u"string",
1464
help=u"Address to listen for requests on")
1465
parser.add_option("-p", u"--port", type=u"int",
1466
help=u"Port number to receive requests on")
1467
parser.add_option("--check", action=u"store_true",
1468
help=u"Run self-test")
1469
parser.add_option("--debug", action=u"store_true",
1470
help=u"Debug mode; run in foreground and log to"
1472
parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1473
u" priority string (see GnuTLS documentation)")
1474
parser.add_option("--servicename", type=u"string",
1475
metavar=u"NAME", help=u"Zeroconf service name")
1476
parser.add_option("--configdir", type=u"string",
1477
default=u"/etc/mandos", metavar=u"DIR",
1478
help=u"Directory to search for configuration"
1480
parser.add_option("--no-dbus", action=u"store_false",
1481
dest=u"use_dbus", help=u"Do not provide D-Bus"
1482
u" system bus interface")
1483
parser.add_option("--no-ipv6", action=u"store_false",
1484
dest=u"use_ipv6", help=u"Do not use IPv6")
1485
options = parser.parse_args()[0]
1708
1487
if options.check:
1713
1492
# Default values for config file for server-global settings
1714
server_defaults = { "interface": "",
1719
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1720
"servicename": "Mandos",
1493
server_defaults = { u"interface": u"",
1498
u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1499
u"servicename": u"Mandos",
1500
u"use_dbus": u"True",
1501
u"use_ipv6": u"True",
1726
1504
# Parse config file for server-global settings
1727
1505
server_config = configparser.SafeConfigParser(server_defaults)
1728
1506
del server_defaults
1729
1507
server_config.read(os.path.join(options.configdir,
1731
1509
# Convert the SafeConfigParser object to a dict
1732
1510
server_settings = server_config.defaults()
1733
1511
# Use the appropriate methods on the non-string config options
1734
for option in ("debug", "use_dbus", "use_ipv6"):
1735
server_settings[option] = server_config.getboolean("DEFAULT",
1512
for option in (u"debug", u"use_dbus", u"use_ipv6"):
1513
server_settings[option] = server_config.getboolean(u"DEFAULT",
1737
1515
if server_settings["port"]:
1738
server_settings["port"] = server_config.getint("DEFAULT",
1516
server_settings["port"] = server_config.getint(u"DEFAULT",
1740
1518
del server_config
1742
1520
# Override the settings from the config file with command line
1743
1521
# options, if set.
1744
for option in ("interface", "address", "port", "debug",
1745
"priority", "servicename", "configdir",
1746
"use_dbus", "use_ipv6", "debuglevel"):
1522
for option in (u"interface", u"address", u"port", u"debug",
1523
u"priority", u"servicename", u"configdir",
1524
u"use_dbus", u"use_ipv6"):
1747
1525
value = getattr(options, option)
1748
1526
if value is not None:
1749
1527
server_settings[option] = value
1757
1535
##################################################################
1759
1537
# For convenience
1760
debug = server_settings["debug"]
1761
debuglevel = server_settings["debuglevel"]
1762
use_dbus = server_settings["use_dbus"]
1763
use_ipv6 = server_settings["use_ipv6"]
1765
if server_settings["servicename"] != "Mandos":
1538
debug = server_settings[u"debug"]
1539
use_dbus = server_settings[u"use_dbus"]
1540
use_ipv6 = server_settings[u"use_ipv6"]
1543
syslogger.setLevel(logging.WARNING)
1544
console.setLevel(logging.WARNING)
1546
if server_settings[u"servicename"] != u"Mandos":
1766
1547
syslogger.setFormatter(logging.Formatter
1767
('Mandos (%s) [%%(process)d]:'
1768
' %%(levelname)s: %%(message)s'
1769
% server_settings["servicename"]))
1548
(u'Mandos (%s) [%%(process)d]:'
1549
u' %%(levelname)s: %%(message)s'
1550
% server_settings[u"servicename"]))
1771
1552
# Parse config file with clients
1772
client_defaults = { "timeout": "1h",
1774
"checker": "fping -q -- %%(host)s",
1776
"approval_delay": "0s",
1777
"approval_duration": "1s",
1553
client_defaults = { u"timeout": u"1h",
1555
u"checker": u"fping -q -- %%(host)s",
1779
1558
client_config = configparser.SafeConfigParser(client_defaults)
1780
client_config.read(os.path.join(server_settings["configdir"],
1559
client_config.read(os.path.join(server_settings[u"configdir"],
1783
1562
global mandos_dbus_service
1784
1563
mandos_dbus_service = None
1786
tcp_server = MandosServer((server_settings["address"],
1787
server_settings["port"]),
1565
tcp_server = MandosServer((server_settings[u"address"],
1566
server_settings[u"port"]),
1789
interface=(server_settings["interface"]
1568
interface=(server_settings[u"interface"]
1791
1570
use_ipv6=use_ipv6,
1792
1571
gnutls_priority=
1793
server_settings["priority"],
1572
server_settings[u"priority"],
1794
1573
use_dbus=use_dbus)
1796
pidfilename = "/var/run/mandos.pid"
1798
pidfile = open(pidfilename, "w")
1800
logger.error("Could not open file %r", pidfilename)
1574
pidfilename = u"/var/run/mandos.pid"
1576
pidfile = open(pidfilename, u"w")
1578
logger.error(u"Could not open file %r", pidfilename)
1803
uid = pwd.getpwnam("_mandos").pw_uid
1804
gid = pwd.getpwnam("_mandos").pw_gid
1581
uid = pwd.getpwnam(u"_mandos").pw_uid
1582
gid = pwd.getpwnam(u"_mandos").pw_gid
1805
1583
except KeyError:
1807
uid = pwd.getpwnam("mandos").pw_uid
1808
gid = pwd.getpwnam("mandos").pw_gid
1585
uid = pwd.getpwnam(u"mandos").pw_uid
1586
gid = pwd.getpwnam(u"mandos").pw_gid
1809
1587
except KeyError:
1811
uid = pwd.getpwnam("nobody").pw_uid
1812
gid = pwd.getpwnam("nobody").pw_gid
1589
uid = pwd.getpwnam(u"nobody").pw_uid
1590
gid = pwd.getpwnam(u"nobody").pw_gid
1813
1591
except KeyError:
1820
1598
if error[0] != errno.EPERM:
1823
if not debug and not debuglevel:
1824
syslogger.setLevel(logging.WARNING)
1825
console.setLevel(logging.WARNING)
1827
level = getattr(logging, debuglevel.upper())
1828
syslogger.setLevel(level)
1829
console.setLevel(level)
1601
# Enable all possible GnuTLS debugging
1832
# Enable all possible GnuTLS debugging
1834
1603
# "Use a log level over 10 to enable all debugging options."
1835
1604
# - GnuTLS manual
1836
1605
gnutls.library.functions.gnutls_global_set_log_level(11)
1838
1607
@gnutls.library.types.gnutls_log_func
1839
1608
def debug_gnutls(level, string):
1840
logger.debug("GnuTLS: %s", string[:-1])
1609
logger.debug(u"GnuTLS: %s", string[:-1])
1842
1611
(gnutls.library.functions
1843
1612
.gnutls_global_set_log_function(debug_gnutls))
1845
# Redirect stdin so all checkers get /dev/null
1846
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1847
os.dup2(null, sys.stdin.fileno())
1851
# No console logging
1852
logger.removeHandler(console)
1854
# Need to fork before connecting to D-Bus
1856
# Close all input and output, do double fork, etc.
1859
1614
global main_loop
1860
1615
# From the Avahi example code
1864
1619
# End of Avahi example code
1867
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1622
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1868
1623
bus, do_not_queue=True)
1869
1624
except dbus.exceptions.NameExistsException, e:
1870
logger.error(unicode(e) + ", disabling D-Bus")
1625
logger.error(unicode(e) + u", disabling D-Bus")
1871
1626
use_dbus = False
1872
server_settings["use_dbus"] = False
1627
server_settings[u"use_dbus"] = False
1873
1628
tcp_server.use_dbus = False
1874
1629
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1875
service = AvahiService(name = server_settings["servicename"],
1876
servicetype = "_mandos._tcp",
1630
service = AvahiService(name = server_settings[u"servicename"],
1631
servicetype = u"_mandos._tcp",
1877
1632
protocol = protocol, bus = bus)
1878
1633
if server_settings["interface"]:
1879
1634
service.interface = (if_nametoindex
1880
(str(server_settings["interface"])))
1882
global multiprocessing_manager
1883
multiprocessing_manager = multiprocessing.Manager()
1635
(str(server_settings[u"interface"])))
1885
1637
client_class = Client
1887
1639
client_class = functools.partial(ClientDBus, bus = bus)
1888
def client_config_items(config, section):
1889
special_settings = {
1890
"approved_by_default":
1891
lambda: config.getboolean(section,
1892
"approved_by_default"),
1894
for name, value in config.items(section):
1896
yield (name, special_settings[name]())
1900
1640
tcp_server.clients.update(set(
1901
1641
client_class(name = section,
1902
config= dict(client_config_items(
1903
client_config, section)))
1642
config= dict(client_config.items(section)))
1904
1643
for section in client_config.sections()))
1905
1644
if not tcp_server.clients:
1906
logger.warning("No clients defined")
1645
logger.warning(u"No clients defined")
1648
# Redirect stdin so all checkers get /dev/null
1649
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1650
os.dup2(null, sys.stdin.fileno())
1654
# No console logging
1655
logger.removeHandler(console)
1656
# Close all input and output, do double fork, etc.
1662
pidfile.write(str(pid) + "\n")
1665
logger.error(u"Could not write to file %r with PID %d",
1668
# "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
1922
1673
signal.signal(signal.SIGINT, signal.SIG_IGN)
1924
1674
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1925
1675
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1928
1678
class MandosDBusService(dbus.service.Object):
1929
1679
"""A D-Bus proxy object"""
1930
1680
def __init__(self):
1931
dbus.service.Object.__init__(self, bus, "/")
1932
_interface = "se.bsnet.fukt.Mandos"
1681
dbus.service.Object.__init__(self, bus, u"/")
1682
_interface = u"se.bsnet.fukt.Mandos"
1934
@dbus.service.signal(_interface, signature="o")
1684
@dbus.service.signal(_interface, signature=u"o")
1935
1685
def ClientAdded(self, objpath):
1939
@dbus.service.signal(_interface, signature="ss")
1689
@dbus.service.signal(_interface, signature=u"ss")
1940
1690
def ClientNotFound(self, fingerprint, address):
1944
@dbus.service.signal(_interface, signature="os")
1694
@dbus.service.signal(_interface, signature=u"os")
1945
1695
def ClientRemoved(self, objpath, name):
1949
@dbus.service.method(_interface, out_signature="ao")
1699
@dbus.service.method(_interface, out_signature=u"ao")
1950
1700
def GetAllClients(self):
1952
1702
return dbus.Array(c.dbus_object_path
1953
1703
for c in tcp_server.clients)
1955
1705
@dbus.service.method(_interface,
1956
out_signature="a{oa{sv}}")
1706
out_signature=u"a{oa{sv}}")
1957
1707
def GetAllClientsWithProperties(self):
1959
1709
return dbus.Dictionary(
1960
((c.dbus_object_path, c.GetAll(""))
1710
((c.dbus_object_path, c.GetAll(u""))
1961
1711
for c in tcp_server.clients),
1712
signature=u"oa{sv}")
1964
@dbus.service.method(_interface, in_signature="o")
1714
@dbus.service.method(_interface, in_signature=u"o")
1965
1715
def RemoveClient(self, object_path):
1967
1717
for c in tcp_server.clients: