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
225
229
if config is None:
227
231
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)
232
self.use_dbus = False # During __init__
235
233
# Uppercase and remove spaces from fingerprint for later
236
234
# comparison purposes with return value from the fingerprint()
261
259
self.disable_initiator_tag = None
262
260
self.checker_callback_tag = None
263
261
self.checker_command = config["checker"]
262
self.last_connect = None
263
# Only now, when this client is initialized, can it show up on
265
self.use_dbus = use_dbus
267
self.dbus_object_path = (dbus.ObjectPath
269
+ self.name.replace(".", "_")))
270
dbus.service.Object.__init__(self, bus,
271
self.dbus_object_path)
265
273
def enable(self):
266
274
"""Start this client's checker and timeout hooks"""
319
327
# Emit D-Bus signal
320
328
self.PropertyChanged(dbus.String(u"checker_running"),
321
329
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",
330
if os.WIFEXITED(condition):
331
exitstatus = os.WEXITSTATUS(condition)
333
logger.info(u"Checker for %(name)s succeeded",
337
logger.info(u"Checker for %(name)s failed",
326
339
if self.use_dbus:
327
340
# Emit D-Bus signal
328
self.CheckerCompleted(dbus.Boolean(True),
329
dbus.UInt16(condition),
341
self.CheckerCompleted(dbus.Int16(exitstatus),
342
dbus.Int64(condition),
330
343
dbus.String(command))
332
elif not os.WIFEXITED(condition):
333
345
logger.warning(u"Checker for %(name)s crashed?",
335
347
if self.use_dbus:
336
348
# 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),
349
self.CheckerCompleted(dbus.Int16(-1),
350
dbus.Int64(condition),
347
351
dbus.String(command))
349
def bump_timeout(self):
353
def checked_ok(self):
350
354
"""Bump up the timeout for this client.
351
355
This should only be called when the client has been seen,
410
414
(self.checker.pid,
411
415
self.checker_callback,
417
# The checker may have completed before the gobject
418
# watch was added. Check for this.
419
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
421
gobject.source_remove(self.checker_callback_tag)
422
self.checker_callback(pid, status, command)
413
423
except OSError, error:
414
424
logger.error(u"Failed to start subprocess: %s",
448
458
return now < (self.last_checked_ok + self.timeout)
450
460
## D-Bus methods & signals
451
_interface = u"org.mandos_system.Mandos.Client"
461
_interface = u"se.bsnet.fukt.Mandos.Client"
453
# BumpTimeout - method
454
BumpTimeout = dbus.service.method(_interface)(bump_timeout)
455
BumpTimeout.__name__ = "BumpTimeout"
464
CheckedOK = dbus.service.method(_interface)(checked_ok)
465
CheckedOK.__name__ = "CheckedOK"
457
467
# CheckerCompleted - signal
458
@dbus.service.signal(_interface, signature="bqs")
459
def CheckerCompleted(self, success, condition, command):
468
@dbus.service.signal(_interface, signature="nxs")
469
def CheckerCompleted(self, exitcode, waitstatus, command):
503
513
dbus.String("checker_running"):
504
514
dbus.Boolean(self.checker is not None,
505
515
variant_level=1),
516
dbus.String("object_path"):
517
dbus.ObjectPath(self.dbus_object_path,
506
519
}, signature="sv")
508
521
# IsStillValid - method
591
604
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
592
605
# ...do the normal thing
593
606
return session.peer_certificate
594
list_size = ctypes.c_uint()
607
list_size = ctypes.c_uint(1)
595
608
cert_list = (gnutls.library.functions
596
609
.gnutls_certificate_get_peers
597
610
(session._c_object, ctypes.byref(list_size)))
611
if not bool(cert_list) and list_size.value != 0:
612
raise gnutls.errors.GNUTLSError("error getting peer"
598
614
if list_size.value == 0:
600
616
cert = cert_list[0]
669
685
# using OpenPGP certificates.
671
687
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
672
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
688
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
674
690
# Use a fallback default, since this MUST be set.
675
691
priority = self.server.settings.get("priority", "NORMAL")
676
692
(gnutls.library.functions
684
700
# Do not run session.bye() here: the session is not
685
701
# established. Just abandon the request.
703
logger.debug(u"Handshake succeeded")
688
705
fpr = fingerprint(peer_certificate(session))
689
706
except (TypeError, gnutls.errors.GNUTLSError), error:
723
741
class IPv6_TCPServer(SocketServer.ForkingMixIn,
724
742
SocketServer.TCPServer, object):
725
"""IPv6 TCP server. Accepts 'None' as address and/or port.
743
"""IPv6-capable TCP server. Accepts 'None' as address and/or port.
727
745
settings: Server settings
728
746
clients: Set() of Client objects
736
754
if "clients" in kwargs:
737
755
self.clients = kwargs["clients"]
738
756
del kwargs["clients"]
757
if "use_ipv6" in kwargs:
758
if not kwargs["use_ipv6"]:
759
self.address_family = socket.AF_INET
760
del kwargs["use_ipv6"]
739
761
self.enabled = False
740
762
super(IPv6_TCPServer, self).__init__(*args, **kwargs)
741
763
def server_bind(self):
755
777
u" bind to interface %s",
756
778
self.settings["interface"])
759
781
# Only bind(2) the socket if we really need to.
760
782
if self.server_address[0] or self.server_address[1]:
761
783
if not self.server_address[0]:
763
self.server_address = (in6addr_any,
784
if self.address_family == socket.AF_INET6:
785
any_address = "::" # in6addr_any
787
any_address = socket.INADDR_ANY
788
self.server_address = (any_address,
764
789
self.server_address[1])
765
790
elif not self.server_address[1]:
766
791
self.server_address = (self.server_address[0],
892
parser = OptionParser(version = "%%prog %s" % version)
917
parser = optparse.OptionParser(version = "%%prog %s" % version)
893
918
parser.add_option("-i", "--interface", type="string",
894
919
metavar="IF", help="Bind to interface IF")
895
920
parser.add_option("-a", "--address", type="string",
914
939
help="Do not provide D-Bus system bus"
941
parser.add_option("--no-ipv6", action="store_false",
942
dest="use_ipv6", help="Do not use IPv6")
916
943
options = parser.parse_args()[0]
918
945
if options.check:
937
965
server_config.read(os.path.join(options.configdir, "mandos.conf"))
938
966
# Convert the SafeConfigParser object to a dict
939
967
server_settings = server_config.defaults()
940
# Use getboolean on the boolean config options
941
server_settings["debug"] = (server_config.getboolean
942
("DEFAULT", "debug"))
943
server_settings["use_dbus"] = (server_config.getboolean
944
("DEFAULT", "use_dbus"))
968
# Use the appropriate methods on the non-string config options
969
server_settings["debug"] = server_config.getboolean("DEFAULT",
971
server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
973
server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
975
if server_settings["port"]:
976
server_settings["port"] = server_config.getint("DEFAULT",
945
978
del server_config
947
980
# Override the settings from the config file with command line
948
981
# options, if set.
949
982
for option in ("interface", "address", "port", "debug",
950
983
"priority", "servicename", "configdir",
984
"use_dbus", "use_ipv6"):
952
985
value = getattr(options, option)
953
986
if value is not None:
954
987
server_settings[option] = value
984
1018
server_settings["port"]),
986
1020
settings=server_settings,
1021
clients=clients, use_ipv6=use_ipv6)
988
1022
pidfilename = "/var/run/mandos.pid"
990
1024
pidfile = open(pidfilename, "w")
991
except IOError, error:
992
1026
logger.error("Could not open file %r", pidfilename)
1011
1045
except OSError, error:
1012
1046
if error[0] != errno.EPERM:
1049
# Enable all possible GnuTLS debugging
1051
# "Use a log level over 10 to enable all debugging options."
1053
gnutls.library.functions.gnutls_global_set_log_level(11)
1055
@gnutls.library.types.gnutls_log_func
1056
def debug_gnutls(level, string):
1057
logger.debug("GnuTLS: %s", string[:-1])
1059
(gnutls.library.functions
1060
.gnutls_global_set_log_function(debug_gnutls))
1063
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1016
1064
service = AvahiService(name = server_settings["servicename"],
1017
servicetype = "_mandos._tcp", )
1065
servicetype = "_mandos._tcp",
1066
protocol = protocol)
1018
1067
if server_settings["interface"]:
1019
1068
service.interface = (if_nametoindex
1020
1069
(server_settings["interface"]))
1031
1080
avahi.DBUS_INTERFACE_SERVER)
1032
1081
# End of Avahi example code
1034
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
1083
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1037
1085
clients.update(Set(Client(name = section,
1092
1140
class MandosServer(dbus.service.Object):
1093
1141
"""A D-Bus proxy object"""
1094
1142
def __init__(self):
1095
dbus.service.Object.__init__(self, bus,
1097
_interface = u"org.mandos_system.Mandos"
1143
dbus.service.Object.__init__(self, bus, "/")
1144
_interface = u"se.bsnet.fukt.Mandos"
1099
1146
@dbus.service.signal(_interface, signature="oa{sv}")
1100
1147
def ClientAdded(self, objpath, properties):
1104
@dbus.service.signal(_interface, signature="o")
1105
def ClientRemoved(self, objpath):
1151
@dbus.service.signal(_interface, signature="os")
1152
def ClientRemoved(self, objpath, name):
1109
1156
@dbus.service.method(_interface, out_signature="ao")
1110
1157
def GetAllClients(self):
1111
1159
return dbus.Array(c.dbus_object_path for c in clients)
1113
1161
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1114
1162
def GetAllClientsWithProperties(self):
1115
1164
return dbus.Dictionary(
1116
1165
((c.dbus_object_path, c.GetAllProperties())
1117
1166
for c in clients),
1118
1167
signature="oa{sv}")
1120
1169
@dbus.service.method(_interface, in_signature="o")
1121
1170
def RemoveClient(self, object_path):
1122
1172
for c in clients:
1123
1173
if c.dbus_object_path == object_path:
1124
1174
clients.remove(c)
1126
1176
c.use_dbus = False
1128
1178
# Emit D-Bus signal
1129
self.ClientRemoved(object_path)
1179
self.ClientRemoved(object_path, c.name)
1132
@dbus.service.method(_interface)
1138
1185
mandos_server = MandosServer()
1140
1187
for client in clients:
1150
1197
# Find out what port we got
1151
1198
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())
1200
logger.info(u"Now listening on address %r, port %d,"
1201
" flowinfo %d, scope_id %d"
1202
% tcp_server.socket.getsockname())
1204
logger.info(u"Now listening on address %r, port %d"
1205
% tcp_server.socket.getsockname())
1155
1207
#service.interface = tcp_server.socket.getsockname()[3]