71
71
logger = logging.Logger('mandos')
72
72
syslogger = (logging.handlers.SysLogHandler
73
73
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
74
74
address = "/dev/log"))
75
75
syslogger.setFormatter(logging.Formatter
76
('Mandos: %(levelname)s: %(message)s'))
76
('Mandos [%(process)d]: %(levelname)s:'
77
78
logger.addHandler(syslogger)
79
80
console = logging.StreamHandler()
80
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
81
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
82
' %(levelname)s: %(message)s'))
82
83
logger.addHandler(console)
84
85
class AvahiError(Exception):
114
115
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
116
servicetype = None, port = None, TXT = None,
116
domain = "", host = "", max_renames = 32768):
117
domain = "", host = "", max_renames = 32768,
118
protocol = avahi.PROTO_UNSPEC):
117
119
self.interface = interface
119
121
self.type = servicetype
157
160
service.name, service.type)
158
161
group.AddService(
159
162
self.interface, # interface
160
avahi.PROTO_INET6, # protocol
163
self.protocol, # protocol
161
164
dbus.UInt32(0), # flags
162
165
self.name, self.type,
163
166
self.domain, self.host,
178
181
class Client(dbus.service.Object):
179
182
"""A representation of a client host served by this server.
181
name: string; from the config file, used in log messages
184
name: string; from the config file, used in log messages and
182
186
fingerprint: string (40 or 32 hexadecimal digits); used to
183
187
uniquely identify the client
184
188
secret: bytestring; sent verbatim (over TLS) to client
201
205
client lives. %() expansions are done at
202
206
runtime with vars(self) as dict, so that for
203
207
instance %(name)s can be used in the command.
208
current_checker_command: string; current running checker_command
204
209
use_dbus: bool(); Whether to provide D-Bus interface and signals
205
210
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
225
230
if config is None:
227
232
logger.debug(u"Creating client %r", self.name)
228
self.use_dbus = use_dbus
230
self.dbus_object_path = (dbus.ObjectPath
232
+ self.name.replace(".", "_")))
233
dbus.service.Object.__init__(self, bus,
234
self.dbus_object_path)
233
self.use_dbus = False # During __init__
235
234
# Uppercase and remove spaces from fingerprint for later
236
235
# comparison purposes with return value from the fingerprint()
261
260
self.disable_initiator_tag = None
262
261
self.checker_callback_tag = None
263
262
self.checker_command = config["checker"]
263
self.current_checker_command = None
264
self.last_connect = None
265
# Only now, when this client is initialized, can it show up on
267
self.use_dbus = use_dbus
269
self.dbus_object_path = (dbus.ObjectPath
271
+ self.name.replace(".", "_")))
272
dbus.service.Object.__init__(self, bus,
273
self.dbus_object_path)
265
275
def enable(self):
266
276
"""Start this client's checker and timeout hooks"""
319
329
# Emit D-Bus signal
320
330
self.PropertyChanged(dbus.String(u"checker_running"),
321
331
dbus.Boolean(False, variant_level=1))
322
if (os.WIFEXITED(condition)
323
and (os.WEXITSTATUS(condition) == 0)):
324
logger.info(u"Checker for %(name)s succeeded",
332
if os.WIFEXITED(condition):
333
exitstatus = os.WEXITSTATUS(condition)
335
logger.info(u"Checker for %(name)s succeeded",
339
logger.info(u"Checker for %(name)s failed",
326
341
if self.use_dbus:
327
342
# Emit D-Bus signal
328
self.CheckerCompleted(dbus.Boolean(True),
329
dbus.UInt16(condition),
343
self.CheckerCompleted(dbus.Int16(exitstatus),
344
dbus.Int64(condition),
330
345
dbus.String(command))
332
elif not os.WIFEXITED(condition):
333
347
logger.warning(u"Checker for %(name)s crashed?",
335
349
if self.use_dbus:
336
350
# Emit D-Bus signal
337
self.CheckerCompleted(dbus.Boolean(False),
338
dbus.UInt16(condition),
339
dbus.String(command))
341
logger.info(u"Checker for %(name)s failed",
345
self.CheckerCompleted(dbus.Boolean(False),
346
dbus.UInt16(condition),
351
self.CheckerCompleted(dbus.Int16(-1),
352
dbus.Int64(condition),
347
353
dbus.String(command))
349
def bump_timeout(self):
355
def checked_ok(self):
350
356
"""Bump up the timeout for this client.
351
357
This should only be called when the client has been seen,
375
381
# checkers alone, the checker would have to take more time
376
382
# than 'timeout' for the client to be declared invalid, which
377
383
# is as it should be.
385
# If a checker exists, make sure it is not a zombie
386
if self.checker is not None:
387
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
389
logger.warning("Checker was a zombie")
390
gobject.source_remove(self.checker_callback_tag)
391
self.checker_callback(pid, status,
392
self.current_checker_command)
393
# Start a new checker if needed
378
394
if self.checker is None:
380
396
# In case checker_command has exactly one % operator
390
406
logger.error(u'Could not format string "%s":'
391
407
u' %s', self.checker_command, error)
392
408
return True # Try again later
409
self.current_checker_command = command
394
411
logger.info(u"Starting checker %r for %s",
395
412
command, self.name)
410
427
(self.checker.pid,
411
428
self.checker_callback,
430
# The checker may have completed before the gobject
431
# watch was added. Check for this.
432
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
434
gobject.source_remove(self.checker_callback_tag)
435
self.checker_callback(pid, status, command)
413
436
except OSError, error:
414
437
logger.error(u"Failed to start subprocess: %s",
448
471
return now < (self.last_checked_ok + self.timeout)
450
473
## D-Bus methods & signals
451
_interface = u"org.mandos_system.Mandos.Client"
474
_interface = u"se.bsnet.fukt.Mandos.Client"
453
# BumpTimeout - method
454
BumpTimeout = dbus.service.method(_interface)(bump_timeout)
455
BumpTimeout.__name__ = "BumpTimeout"
477
CheckedOK = dbus.service.method(_interface)(checked_ok)
478
CheckedOK.__name__ = "CheckedOK"
457
480
# CheckerCompleted - signal
458
@dbus.service.signal(_interface, signature="bqs")
459
def CheckerCompleted(self, success, condition, command):
481
@dbus.service.signal(_interface, signature="nxs")
482
def CheckerCompleted(self, exitcode, waitstatus, command):
503
526
dbus.String("checker_running"):
504
527
dbus.Boolean(self.checker is not None,
505
528
variant_level=1),
529
dbus.String("object_path"):
530
dbus.ObjectPath(self.dbus_object_path,
506
532
}, signature="sv")
508
534
# IsStillValid - method
591
617
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
592
618
# ...do the normal thing
593
619
return session.peer_certificate
594
list_size = ctypes.c_uint()
620
list_size = ctypes.c_uint(1)
595
621
cert_list = (gnutls.library.functions
596
622
.gnutls_certificate_get_peers
597
623
(session._c_object, ctypes.byref(list_size)))
624
if not bool(cert_list) and list_size.value != 0:
625
raise gnutls.errors.GNUTLSError("error getting peer"
598
627
if list_size.value == 0:
600
629
cert = cert_list[0]
669
698
# using OpenPGP certificates.
671
700
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
672
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
701
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
674
703
# Use a fallback default, since this MUST be set.
675
704
priority = self.server.settings.get("priority", "NORMAL")
676
705
(gnutls.library.functions
684
713
# Do not run session.bye() here: the session is not
685
714
# established. Just abandon the request.
716
logger.debug(u"Handshake succeeded")
688
718
fpr = fingerprint(peer_certificate(session))
689
719
except (TypeError, gnutls.errors.GNUTLSError), error:
723
754
class IPv6_TCPServer(SocketServer.ForkingMixIn,
724
755
SocketServer.TCPServer, object):
725
"""IPv6 TCP server. Accepts 'None' as address and/or port.
756
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
727
758
settings: Server settings
728
759
clients: Set() of Client objects
736
767
if "clients" in kwargs:
737
768
self.clients = kwargs["clients"]
738
769
del kwargs["clients"]
770
if "use_ipv6" in kwargs:
771
if not kwargs["use_ipv6"]:
772
self.address_family = socket.AF_INET
773
del kwargs["use_ipv6"]
739
774
self.enabled = False
740
775
super(IPv6_TCPServer, self).__init__(*args, **kwargs)
741
776
def server_bind(self):
755
790
u" bind to interface %s",
756
791
self.settings["interface"])
759
794
# Only bind(2) the socket if we really need to.
760
795
if self.server_address[0] or self.server_address[1]:
761
796
if not self.server_address[0]:
763
self.server_address = (in6addr_any,
797
if self.address_family == socket.AF_INET6:
798
any_address = "::" # in6addr_any
800
any_address = socket.INADDR_ANY
801
self.server_address = (any_address,
764
802
self.server_address[1])
765
803
elif not self.server_address[1]:
766
804
self.server_address = (self.server_address[0],
912
950
parser.add_option("--no-dbus", action="store_false",
914
952
help=optparse.SUPPRESS_HELP) # XXX: Not done yet
953
parser.add_option("--no-ipv6", action="store_false",
954
dest="use_ipv6", help="Do not use IPv6")
915
955
options = parser.parse_args()[0]
917
957
if options.check:
936
977
server_config.read(os.path.join(options.configdir, "mandos.conf"))
937
978
# Convert the SafeConfigParser object to a dict
938
979
server_settings = server_config.defaults()
939
# Use getboolean on the boolean config options
940
server_settings["debug"] = (server_config.getboolean
941
("DEFAULT", "debug"))
942
server_settings["use_dbus"] = (server_config.getboolean
943
("DEFAULT", "use_dbus"))
980
# Use the appropriate methods on the non-string config options
981
server_settings["debug"] = server_config.getboolean("DEFAULT",
983
server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
985
server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
987
if server_settings["port"]:
988
server_settings["port"] = server_config.getint("DEFAULT",
944
990
del server_config
946
992
# Override the settings from the config file with command line
947
993
# options, if set.
948
994
for option in ("interface", "address", "port", "debug",
949
995
"priority", "servicename", "configdir",
996
"use_dbus", "use_ipv6"):
951
997
value = getattr(options, option)
952
998
if value is not None:
953
999
server_settings[option] = value
958
1004
debug = server_settings["debug"]
959
1005
use_dbus = server_settings["use_dbus"]
960
1006
use_dbus = False # XXX: Not done yet
1007
use_ipv6 = server_settings["use_ipv6"]
963
1010
syslogger.setLevel(logging.WARNING)
984
1031
server_settings["port"]),
986
1033
settings=server_settings,
1034
clients=clients, use_ipv6=use_ipv6)
988
1035
pidfilename = "/var/run/mandos.pid"
990
1037
pidfile = open(pidfilename, "w")
991
except IOError, error:
992
1039
logger.error("Could not open file %r", pidfilename)
1011
1058
except OSError, error:
1012
1059
if error[0] != errno.EPERM:
1062
# Enable all possible GnuTLS debugging
1064
# "Use a log level over 10 to enable all debugging options."
1066
gnutls.library.functions.gnutls_global_set_log_level(11)
1068
@gnutls.library.types.gnutls_log_func
1069
def debug_gnutls(level, string):
1070
logger.debug("GnuTLS: %s", string[:-1])
1072
(gnutls.library.functions
1073
.gnutls_global_set_log_function(debug_gnutls))
1076
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1016
1077
service = AvahiService(name = server_settings["servicename"],
1017
servicetype = "_mandos._tcp", )
1078
servicetype = "_mandos._tcp",
1079
protocol = protocol)
1018
1080
if server_settings["interface"]:
1019
1081
service.interface = (if_nametoindex
1020
1082
(server_settings["interface"]))
1031
1093
avahi.DBUS_INTERFACE_SERVER)
1032
1094
# End of Avahi example code
1034
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
1096
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1037
1098
clients.update(Set(Client(name = section,
1092
1153
class MandosServer(dbus.service.Object):
1093
1154
"""A D-Bus proxy object"""
1094
1155
def __init__(self):
1095
dbus.service.Object.__init__(self, bus,
1097
_interface = u"org.mandos_system.Mandos"
1156
dbus.service.Object.__init__(self, bus, "/")
1157
_interface = u"se.bsnet.fukt.Mandos"
1099
1159
@dbus.service.signal(_interface, signature="oa{sv}")
1100
1160
def ClientAdded(self, objpath, properties):
1104
@dbus.service.signal(_interface, signature="o")
1105
def ClientRemoved(self, objpath):
1164
@dbus.service.signal(_interface, signature="os")
1165
def ClientRemoved(self, objpath, name):
1109
1169
@dbus.service.method(_interface, out_signature="ao")
1110
1170
def GetAllClients(self):
1111
1172
return dbus.Array(c.dbus_object_path for c in clients)
1113
1174
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1114
1175
def GetAllClientsWithProperties(self):
1115
1177
return dbus.Dictionary(
1116
1178
((c.dbus_object_path, c.GetAllProperties())
1117
1179
for c in clients),
1118
1180
signature="oa{sv}")
1120
1182
@dbus.service.method(_interface, in_signature="o")
1121
1183
def RemoveClient(self, object_path):
1122
1185
for c in clients:
1123
1186
if c.dbus_object_path == object_path:
1124
1187
clients.remove(c)
1126
1189
c.use_dbus = False
1128
1191
# Emit D-Bus signal
1129
self.ClientRemoved(object_path)
1192
self.ClientRemoved(object_path, c.name)
1132
@dbus.service.method(_interface)
1138
1198
mandos_server = MandosServer()
1140
1200
for client in clients:
1150
1210
# Find out what port we got
1151
1211
service.port = tcp_server.socket.getsockname()[1]
1152
logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
1153
u" scope_id %d" % tcp_server.socket.getsockname())
1213
logger.info(u"Now listening on address %r, port %d,"
1214
" flowinfo %d, scope_id %d"
1215
% tcp_server.socket.getsockname())
1217
logger.info(u"Now listening on address %r, port %d"
1218
% tcp_server.socket.getsockname())
1155
1220
#service.interface = tcp_server.socket.getsockname()[3]