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 [%(process)d]: %(levelname)s:'
76
('Mandos: %(levelname)s: %(message)s'))
78
77
logger.addHandler(syslogger)
80
79
console = logging.StreamHandler()
81
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
82
' %(levelname)s: %(message)s'))
80
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
83
82
logger.addHandler(console)
85
84
class AvahiError(Exception):
179
178
class Client(dbus.service.Object):
180
179
"""A representation of a client host served by this server.
182
name: string; from the config file, used in log messages and
181
name: string; from the config file, used in log messages
184
182
fingerprint: string (40 or 32 hexadecimal digits); used to
185
183
uniquely identify the client
186
184
secret: bytestring; sent verbatim (over TLS) to client
227
225
if config is None:
229
227
logger.debug(u"Creating client %r", self.name)
230
self.use_dbus = False # During __init__
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)
231
235
# Uppercase and remove spaces from fingerprint for later
232
236
# comparison purposes with return value from the fingerprint()
257
261
self.disable_initiator_tag = None
258
262
self.checker_callback_tag = None
259
263
self.checker_command = config["checker"]
260
self.last_connect = None
261
# Only now, when this client is initialized, can it show up on
263
self.use_dbus = use_dbus
265
self.dbus_object_path = (dbus.ObjectPath
267
+ self.name.replace(".", "_")))
268
dbus.service.Object.__init__(self, bus,
269
self.dbus_object_path)
271
265
def enable(self):
272
266
"""Start this client's checker and timeout hooks"""
325
319
# Emit D-Bus signal
326
320
self.PropertyChanged(dbus.String(u"checker_running"),
327
321
dbus.Boolean(False, variant_level=1))
328
if os.WIFEXITED(condition):
329
exitstatus = os.WEXITSTATUS(condition)
331
logger.info(u"Checker for %(name)s succeeded",
335
logger.info(u"Checker for %(name)s failed",
322
if (os.WIFEXITED(condition)
323
and (os.WEXITSTATUS(condition) == 0)):
324
logger.info(u"Checker for %(name)s succeeded",
337
326
if self.use_dbus:
338
327
# Emit D-Bus signal
339
self.CheckerCompleted(dbus.Int16(exitstatus),
340
dbus.Int64(condition),
328
self.CheckerCompleted(dbus.Boolean(True),
329
dbus.UInt16(condition),
341
330
dbus.String(command))
332
elif not os.WIFEXITED(condition):
343
333
logger.warning(u"Checker for %(name)s crashed?",
345
335
if self.use_dbus:
346
336
# Emit D-Bus signal
347
self.CheckerCompleted(dbus.Int16(-1),
348
dbus.Int64(condition),
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
347
dbus.String(command))
351
def checked_ok(self):
349
def bump_timeout(self):
352
350
"""Bump up the timeout for this client.
353
351
This should only be called when the client has been seen,
450
448
return now < (self.last_checked_ok + self.timeout)
452
450
## D-Bus methods & signals
453
_interface = u"se.bsnet.fukt.Mandos.Client"
451
_interface = u"org.mandos_system.Mandos.Client"
456
CheckedOK = dbus.service.method(_interface)(checked_ok)
457
CheckedOK.__name__ = "CheckedOK"
453
# BumpTimeout - method
454
BumpTimeout = dbus.service.method(_interface)(bump_timeout)
455
BumpTimeout.__name__ = "BumpTimeout"
459
457
# CheckerCompleted - signal
460
@dbus.service.signal(_interface, signature="nxs")
461
def CheckerCompleted(self, exitcode, waitstatus, command):
458
@dbus.service.signal(_interface, signature="bqs")
459
def CheckerCompleted(self, success, condition, command):
505
503
dbus.String("checker_running"):
506
504
dbus.Boolean(self.checker is not None,
507
505
variant_level=1),
508
dbus.String("object_path"):
509
dbus.ObjectPath(self.dbus_object_path,
511
506
}, signature="sv")
513
508
# IsStillValid - method
596
591
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
597
592
# ...do the normal thing
598
593
return session.peer_certificate
599
list_size = ctypes.c_uint(1)
594
list_size = ctypes.c_uint()
600
595
cert_list = (gnutls.library.functions
601
596
.gnutls_certificate_get_peers
602
597
(session._c_object, ctypes.byref(list_size)))
603
if not bool(cert_list) and list_size.value != 0:
604
raise gnutls.errors.GNUTLSError("error getting peer"
606
598
if list_size.value == 0:
608
600
cert = cert_list[0]
677
669
# using OpenPGP certificates.
679
671
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
680
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
672
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
682
674
# Use a fallback default, since this MUST be set.
683
675
priority = self.server.settings.get("priority", "NORMAL")
684
676
(gnutls.library.functions
692
684
# Do not run session.bye() here: the session is not
693
685
# established. Just abandon the request.
695
logger.debug(u"Handshake succeeded")
697
688
fpr = fingerprint(peer_certificate(session))
698
689
except (TypeError, gnutls.errors.GNUTLSError), error:
765
755
u" bind to interface %s",
766
756
self.settings["interface"])
769
759
# Only bind(2) the socket if we really need to.
770
760
if self.server_address[0] or self.server_address[1]:
771
761
if not self.server_address[0]:
902
parser = optparse.OptionParser(version = "%%prog %s" % version)
892
parser = OptionParser(version = "%%prog %s" % version)
903
893
parser.add_option("-i", "--interface", type="string",
904
894
metavar="IF", help="Bind to interface IF")
905
895
parser.add_option("-a", "--address", type="string",
947
937
server_config.read(os.path.join(options.configdir, "mandos.conf"))
948
938
# Convert the SafeConfigParser object to a dict
949
939
server_settings = server_config.defaults()
950
# Use the appropriate methods on the non-string config options
951
server_settings["debug"] = server_config.getboolean("DEFAULT",
953
server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
955
if server_settings["port"]:
956
server_settings["port"] = server_config.getint("DEFAULT",
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"))
958
945
del server_config
960
947
# Override the settings from the config file with command line
1024
1011
except OSError, error:
1025
1012
if error[0] != errno.EPERM:
1028
# Enable all possible GnuTLS debugging
1030
# "Use a log level over 10 to enable all debugging options."
1032
gnutls.library.functions.gnutls_global_set_log_level(11)
1034
@gnutls.library.types.gnutls_log_func
1035
def debug_gnutls(level, string):
1036
logger.debug("GnuTLS: %s", string[:-1])
1038
(gnutls.library.functions
1039
.gnutls_global_set_log_function(debug_gnutls))
1042
1016
service = AvahiService(name = server_settings["servicename"],
1043
1017
servicetype = "_mandos._tcp", )
1057
1031
avahi.DBUS_INTERFACE_SERVER)
1058
1032
# End of Avahi example code
1060
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1034
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
1062
1037
clients.update(Set(Client(name = section,
1117
1092
class MandosServer(dbus.service.Object):
1118
1093
"""A D-Bus proxy object"""
1119
1094
def __init__(self):
1120
dbus.service.Object.__init__(self, bus, "/")
1121
_interface = u"se.bsnet.fukt.Mandos"
1095
dbus.service.Object.__init__(self, bus,
1097
_interface = u"org.mandos_system.Mandos"
1123
1099
@dbus.service.signal(_interface, signature="oa{sv}")
1124
1100
def ClientAdded(self, objpath, properties):
1128
@dbus.service.signal(_interface, signature="os")
1129
def ClientRemoved(self, objpath, name):
1104
@dbus.service.signal(_interface, signature="o")
1105
def ClientRemoved(self, objpath):
1133
1109
@dbus.service.method(_interface, out_signature="ao")
1134
1110
def GetAllClients(self):
1136
1111
return dbus.Array(c.dbus_object_path for c in clients)
1138
1113
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1139
1114
def GetAllClientsWithProperties(self):
1141
1115
return dbus.Dictionary(
1142
1116
((c.dbus_object_path, c.GetAllProperties())
1143
1117
for c in clients),
1144
1118
signature="oa{sv}")
1146
1120
@dbus.service.method(_interface, in_signature="o")
1147
1121
def RemoveClient(self, object_path):
1149
1122
for c in clients:
1150
1123
if c.dbus_object_path == object_path:
1151
1124
clients.remove(c)
1153
1126
c.use_dbus = False
1155
1128
# Emit D-Bus signal
1156
self.ClientRemoved(object_path, c.name)
1129
self.ClientRemoved(object_path)
1132
@dbus.service.method(_interface)
1162
1138
mandos_server = MandosServer()
1164
1140
for client in clients: