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):
86
def __init__(self, value, *args, **kwargs):
85
def __init__(self, value):
88
super(AvahiError, self).__init__(value, *args, **kwargs)
89
def __unicode__(self):
90
return unicode(repr(self.value))
87
super(AvahiError, self).__init__()
89
return repr(self.value)
92
91
class AvahiServiceError(AvahiError):
115
114
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
116
115
servicetype = None, port = None, TXT = None,
117
domain = "", host = "", max_renames = 32768,
118
protocol = avahi.PROTO_UNSPEC):
116
domain = "", host = "", max_renames = 32768):
119
117
self.interface = interface
121
119
self.type = servicetype
126
124
self.rename_count = 0
127
125
self.max_renames = max_renames
128
self.protocol = protocol
129
126
def rename(self):
130
127
"""Derived from the Avahi example code"""
131
128
if self.rename_count >= self.max_renames:
132
129
logger.critical(u"No suitable Zeroconf service name found"
133
130
u" after %i retries, exiting.",
134
131
self.rename_count)
135
raise AvahiServiceError(u"Too many renames")
132
raise AvahiServiceError("Too many renames")
136
133
self.name = server.GetAlternativeServiceName(self.name)
137
134
logger.info(u"Changing Zeroconf service name to %r ...",
181
178
class Client(dbus.service.Object):
182
179
"""A representation of a client host served by this server.
184
name: string; from the config file, used in log messages and
181
name: string; from the config file, used in log messages
186
182
fingerprint: string (40 or 32 hexadecimal digits); used to
187
183
uniquely identify the client
188
184
secret: bytestring; sent verbatim (over TLS) to client
205
201
client lives. %() expansions are done at
206
202
runtime with vars(self) as dict, so that for
207
203
instance %(name)s can be used in the command.
208
current_checker_command: string; current running checker_command
209
use_dbus: bool(); Whether to provide D-Bus interface and signals
210
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
204
dbus_object_path: dbus.ObjectPath
206
_timeout: Real variable for 'timeout'
207
_interval: Real variable for 'interval'
208
_timeout_milliseconds: Used when calling gobject.timeout_add()
209
_interval_milliseconds: - '' -
212
def timeout_milliseconds(self):
213
"Return the 'timeout' attribute in milliseconds"
214
return ((self.timeout.days * 24 * 60 * 60 * 1000)
215
+ (self.timeout.seconds * 1000)
216
+ (self.timeout.microseconds // 1000))
218
def interval_milliseconds(self):
219
"Return the 'interval' attribute in milliseconds"
220
return ((self.interval.days * 24 * 60 * 60 * 1000)
221
+ (self.interval.seconds * 1000)
222
+ (self.interval.microseconds // 1000))
224
def __init__(self, name = None, disable_hook=None, config=None,
211
def _set_timeout(self, timeout):
212
"Setter function for the 'timeout' attribute"
213
self._timeout = timeout
214
self._timeout_milliseconds = ((self.timeout.days
215
* 24 * 60 * 60 * 1000)
216
+ (self.timeout.seconds * 1000)
217
+ (self.timeout.microseconds
220
self.PropertyChanged(dbus.String(u"timeout"),
221
(dbus.UInt64(self._timeout_milliseconds,
223
timeout = property(lambda self: self._timeout, _set_timeout)
226
def _set_interval(self, interval):
227
"Setter function for the 'interval' attribute"
228
self._interval = interval
229
self._interval_milliseconds = ((self.interval.days
230
* 24 * 60 * 60 * 1000)
231
+ (self.interval.seconds
233
+ (self.interval.microseconds
236
self.PropertyChanged(dbus.String(u"interval"),
237
(dbus.UInt64(self._interval_milliseconds,
239
interval = property(lambda self: self._interval, _set_interval)
242
def __init__(self, name = None, disable_hook=None, config=None):
226
243
"""Note: the 'checker' key in 'config' sets the
227
244
'checker_command' attribute and *not* the 'checker'
246
self.dbus_object_path = (dbus.ObjectPath
248
+ name.replace(".", "_")))
249
dbus.service.Object.__init__(self, bus,
250
self.dbus_object_path)
230
251
if config is None:
232
254
logger.debug(u"Creating client %r", self.name)
233
self.use_dbus = False # During __init__
234
255
# Uppercase and remove spaces from fingerprint for later
235
256
# comparison purposes with return value from the fingerprint()
260
281
self.disable_initiator_tag = None
261
282
self.checker_callback_tag = None
262
283
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)
275
285
def enable(self):
276
286
"""Start this client's checker and timeout hooks"""
278
288
# Schedule a new checker to be started an 'interval' from now,
279
289
# and every interval from then on.
280
290
self.checker_initiator_tag = (gobject.timeout_add
281
(self.interval_milliseconds(),
291
(self._interval_milliseconds,
282
292
self.start_checker))
283
293
# Also start a new checker *right now*.
284
294
self.start_checker()
285
295
# Schedule a disable() when 'timeout' has passed
286
296
self.disable_initiator_tag = (gobject.timeout_add
287
(self.timeout_milliseconds(),
297
(self._timeout_milliseconds,
289
299
self.enabled = True
292
self.PropertyChanged(dbus.String(u"enabled"),
293
dbus.Boolean(True, variant_level=1))
294
self.PropertyChanged(dbus.String(u"last_enabled"),
295
(_datetime_to_dbus(self.last_enabled,
301
self.PropertyChanged(dbus.String(u"enabled"),
302
dbus.Boolean(True, variant_level=1))
303
self.PropertyChanged(dbus.String(u"last_enabled"),
304
(_datetime_to_dbus(self.last_enabled,
298
307
def disable(self):
299
308
"""Disable this client."""
325
333
"""The checker has completed, so take appropriate actions."""
326
334
self.checker_callback_tag = None
327
335
self.checker = None
337
self.PropertyChanged(dbus.String(u"checker_running"),
338
dbus.Boolean(False, variant_level=1))
339
if (os.WIFEXITED(condition)
340
and (os.WEXITSTATUS(condition) == 0)):
341
logger.info(u"Checker for %(name)s succeeded",
329
343
# Emit D-Bus signal
330
self.PropertyChanged(dbus.String(u"checker_running"),
331
dbus.Boolean(False, variant_level=1))
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",
343
self.CheckerCompleted(dbus.Int16(exitstatus),
344
dbus.Int64(condition),
345
dbus.String(command))
344
self.CheckerCompleted(dbus.Boolean(True),
345
dbus.UInt16(condition),
346
dbus.String(command))
348
elif not os.WIFEXITED(condition):
347
349
logger.warning(u"Checker for %(name)s crashed?",
351
self.CheckerCompleted(dbus.Int16(-1),
352
dbus.Int64(condition),
353
dbus.String(command))
352
self.CheckerCompleted(dbus.Boolean(False),
353
dbus.UInt16(condition),
354
dbus.String(command))
356
logger.info(u"Checker for %(name)s failed",
359
self.CheckerCompleted(dbus.Boolean(False),
360
dbus.UInt16(condition),
361
dbus.String(command))
355
def checked_ok(self):
363
def bump_timeout(self):
356
364
"""Bump up the timeout for this client.
357
365
This should only be called when the client has been seen,
360
368
self.last_checked_ok = datetime.datetime.utcnow()
361
369
gobject.source_remove(self.disable_initiator_tag)
362
370
self.disable_initiator_tag = (gobject.timeout_add
363
(self.timeout_milliseconds(),
371
(self._timeout_milliseconds,
367
self.PropertyChanged(
368
dbus.String(u"last_checked_ok"),
369
(_datetime_to_dbus(self.last_checked_ok,
373
self.PropertyChanged(dbus.String(u"last_checked_ok"),
374
(_datetime_to_dbus(self.last_checked_ok,
372
377
def start_checker(self):
373
378
"""Start a new checker subprocess if one is not running.
381
386
# checkers alone, the checker would have to take more time
382
387
# than 'timeout' for the client to be declared invalid, which
383
388
# 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
394
389
if self.checker is None:
396
391
# In case checker_command has exactly one % operator
417
411
self.checker = subprocess.Popen(command,
419
413
shell=True, cwd="/")
422
self.CheckerStarted(command)
423
self.PropertyChanged(
424
dbus.String("checker_running"),
425
dbus.Boolean(True, variant_level=1))
415
self.CheckerStarted(command)
416
self.PropertyChanged(dbus.String("checker_running"),
417
dbus.Boolean(True, variant_level=1))
426
418
self.checker_callback_tag = (gobject.child_watch_add
427
419
(self.checker.pid,
428
420
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)
436
422
except OSError, error:
437
423
logger.error(u"Failed to start subprocess: %s",
471
456
return now < (self.last_checked_ok + self.timeout)
473
458
## D-Bus methods & signals
474
_interface = u"se.bsnet.fukt.Mandos.Client"
459
_interface = u"org.mandos_system.Mandos.Client"
477
CheckedOK = dbus.service.method(_interface)(checked_ok)
478
CheckedOK.__name__ = "CheckedOK"
461
# BumpTimeout - method
462
BumpTimeout = dbus.service.method(_interface)(bump_timeout)
463
BumpTimeout.__name__ = "BumpTimeout"
480
465
# CheckerCompleted - signal
481
@dbus.service.signal(_interface, signature="nxs")
482
def CheckerCompleted(self, exitcode, waitstatus, command):
466
@dbus.service.signal(_interface, signature="bqs")
467
def CheckerCompleted(self, success, condition, command):
515
500
if self.last_checked_ok is not None
516
501
else dbus.Boolean (False, variant_level=1)),
517
502
dbus.String("timeout"):
518
dbus.UInt64(self.timeout_milliseconds(),
503
dbus.UInt64(self._timeout_milliseconds,
519
504
variant_level=1),
520
505
dbus.String("interval"):
521
dbus.UInt64(self.interval_milliseconds(),
506
dbus.UInt64(self._interval_milliseconds,
522
507
variant_level=1),
523
508
dbus.String("checker"):
524
509
dbus.String(self.checker_command,
547
529
def SetChecker(self, checker):
548
530
"D-Bus setter method"
549
531
self.checker_command = checker
551
self.PropertyChanged(dbus.String(u"checker"),
552
dbus.String(self.checker_command,
555
533
# SetHost - method
556
534
@dbus.service.method(_interface, in_signature="s")
557
535
def SetHost(self, host):
558
536
"D-Bus setter method"
561
self.PropertyChanged(dbus.String(u"host"),
562
dbus.String(self.host, variant_level=1))
564
539
# SetInterval - method
565
540
@dbus.service.method(_interface, in_signature="t")
566
541
def SetInterval(self, milliseconds):
567
self.interval = datetime.timedelta(0, 0, 0, milliseconds)
569
self.PropertyChanged(dbus.String(u"interval"),
570
(dbus.UInt64(self.interval_milliseconds(),
542
self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
573
544
# SetSecret - method
574
545
@dbus.service.method(_interface, in_signature="ay",
581
552
@dbus.service.method(_interface, in_signature="t")
582
553
def SetTimeout(self, milliseconds):
583
554
self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
585
self.PropertyChanged(dbus.String(u"timeout"),
586
(dbus.UInt64(self.timeout_milliseconds(),
589
556
# Enable - method
590
557
Enable = dbus.service.method(_interface)(enable)
617
584
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
618
585
# ...do the normal thing
619
586
return session.peer_certificate
620
list_size = ctypes.c_uint(1)
587
list_size = ctypes.c_uint()
621
588
cert_list = (gnutls.library.functions
622
589
.gnutls_certificate_get_peers
623
590
(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"
627
591
if list_size.value == 0:
629
593
cert = cert_list[0]
698
662
# using OpenPGP certificates.
700
664
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
701
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
665
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
703
667
# Use a fallback default, since this MUST be set.
704
668
priority = self.server.settings.get("priority", "NORMAL")
705
669
(gnutls.library.functions
790
748
u" bind to interface %s",
791
749
self.settings["interface"])
794
752
# Only bind(2) the socket if we really need to.
795
753
if self.server_address[0] or self.server_address[1]:
796
754
if not self.server_address[0]:
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,
756
self.server_address = (in6addr_any,
802
757
self.server_address[1])
803
758
elif not self.server_address[1]:
804
759
self.server_address = (self.server_address[0],
930
parser = optparse.OptionParser(version = "%%prog %s" % version)
885
parser = OptionParser(version = "%%prog %s" % version)
931
886
parser.add_option("-i", "--interface", type="string",
932
887
metavar="IF", help="Bind to interface IF")
933
888
parser.add_option("-a", "--address", type="string",
934
889
help="Address to listen for requests on")
935
890
parser.add_option("-p", "--port", type="int",
936
891
help="Port number to receive requests on")
937
parser.add_option("--check", action="store_true",
892
parser.add_option("--check", action="store_true", default=False,
938
893
help="Run self-test")
939
894
parser.add_option("--debug", action="store_true",
940
895
help="Debug mode; run in foreground and log to"
947
902
default="/etc/mandos", metavar="DIR",
948
903
help="Directory to search for configuration"
950
parser.add_option("--no-dbus", action="store_false",
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")
955
905
options = parser.parse_args()[0]
957
907
if options.check:
977
925
server_config.read(os.path.join(options.configdir, "mandos.conf"))
978
926
# Convert the SafeConfigParser object to a dict
979
927
server_settings = server_config.defaults()
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",
928
# Use getboolean on the boolean config option
929
server_settings["debug"] = (server_config.getboolean
930
("DEFAULT", "debug"))
990
931
del server_config
992
933
# Override the settings from the config file with command line
993
934
# options, if set.
994
935
for option in ("interface", "address", "port", "debug",
995
"priority", "servicename", "configdir",
996
"use_dbus", "use_ipv6"):
936
"priority", "servicename", "configdir"):
997
937
value = getattr(options, option)
998
938
if value is not None:
999
939
server_settings[option] = value
1001
941
# Now we have our good server settings in "server_settings"
1004
943
debug = server_settings["debug"]
1005
use_dbus = server_settings["use_dbus"]
1006
use_dbus = False # XXX: Not done yet
1007
use_ipv6 = server_settings["use_ipv6"]
1010
946
syslogger.setLevel(logging.WARNING)
1031
967
server_settings["port"]),
1033
969
settings=server_settings,
1034
clients=clients, use_ipv6=use_ipv6)
1035
971
pidfilename = "/var/run/mandos.pid"
1037
973
pidfile = open(pidfilename, "w")
974
except IOError, error:
1039
975
logger.error("Could not open file %r", pidfilename)
1042
978
uid = pwd.getpwnam("_mandos").pw_uid
981
uid = pwd.getpwnam("mandos").pw_uid
984
uid = pwd.getpwnam("nobody").pw_uid
1043
988
gid = pwd.getpwnam("_mandos").pw_gid
1044
989
except KeyError:
1046
uid = pwd.getpwnam("mandos").pw_uid
1047
991
gid = pwd.getpwnam("mandos").pw_gid
1048
992
except KeyError:
1050
uid = pwd.getpwnam("nobody").pw_uid
1051
994
gid = pwd.getpwnam("nogroup").pw_gid
1052
995
except KeyError:
1058
1000
except OSError, error:
1059
1001
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
1077
1005
service = AvahiService(name = server_settings["servicename"],
1078
servicetype = "_mandos._tcp",
1079
protocol = protocol)
1006
servicetype = "_mandos._tcp", )
1080
1007
if server_settings["interface"]:
1081
1008
service.interface = (if_nametoindex
1082
1009
(server_settings["interface"]))
1092
1019
avahi.DBUS_PATH_SERVER),
1093
1020
avahi.DBUS_INTERFACE_SERVER)
1094
1021
# End of Avahi example code
1096
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1022
bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
1098
1024
clients.update(Set(Client(name = section,
1100
= dict(client_config.items(section)),
1101
use_dbus = use_dbus)
1026
= dict(client_config.items(section)))
1102
1027
for section in client_config.sections()))
1103
1028
if not clients:
1104
logger.warning(u"No clients defined")
1029
logger.critical(u"No clients defined")
1107
1033
# Redirect stdin so all checkers get /dev/null
1149
1075
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1150
1076
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1153
class MandosServer(dbus.service.Object):
1154
"""A D-Bus proxy object"""
1156
dbus.service.Object.__init__(self, bus, "/")
1157
_interface = u"se.bsnet.fukt.Mandos"
1159
@dbus.service.signal(_interface, signature="oa{sv}")
1160
def ClientAdded(self, objpath, properties):
1164
@dbus.service.signal(_interface, signature="os")
1165
def ClientRemoved(self, objpath, name):
1169
@dbus.service.method(_interface, out_signature="ao")
1170
def GetAllClients(self):
1172
return dbus.Array(c.dbus_object_path for c in clients)
1174
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1175
def GetAllClientsWithProperties(self):
1177
return dbus.Dictionary(
1178
((c.dbus_object_path, c.GetAllProperties())
1182
@dbus.service.method(_interface, in_signature="o")
1183
def RemoveClient(self, object_path):
1186
if c.dbus_object_path == object_path:
1188
# Don't signal anything except ClientRemoved
1192
self.ClientRemoved(object_path, c.name)
1198
mandos_server = MandosServer()
1078
class MandosServer(dbus.service.Object):
1079
"""A D-Bus proxy object"""
1081
dbus.service.Object.__init__(self, bus,
1083
_interface = u"org.mandos_system.Mandos"
1085
@dbus.service.signal(_interface, signature="oa{sv}")
1086
def ClientAdded(self, objpath, properties):
1090
@dbus.service.signal(_interface, signature="o")
1091
def ClientRemoved(self, objpath):
1095
@dbus.service.method(_interface, out_signature="ao")
1096
def GetAllClients(self):
1097
return dbus.Array(c.dbus_object_path for c in clients)
1099
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1100
def GetAllClientsWithProperties(self):
1101
return dbus.Dictionary(
1102
((c.dbus_object_path, c.GetAllProperties())
1106
@dbus.service.method(_interface, in_signature="o")
1107
def RemoveClient(self, object_path):
1109
if c.dbus_object_path == object_path:
1117
mandos_server = MandosServer()
1200
1119
for client in clients:
1203
mandos_server.ClientAdded(client.dbus_object_path,
1204
client.GetAllProperties())
1121
mandos_server.ClientAdded(client.dbus_object_path,
1122
client.GetAllProperties())
1205
1123
client.enable()
1207
1125
tcp_server.enable()
1210
1128
# Find out what port we got
1211
1129
service.port = tcp_server.socket.getsockname()[1]
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())
1130
logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
1131
u" scope_id %d" % tcp_server.socket.getsockname())
1220
1133
#service.interface = tcp_server.socket.getsockname()[3]
1237
1150
logger.debug(u"Starting main loop")
1238
1151
main_loop.run()
1239
1152
except AvahiError, error:
1240
logger.critical(u"AvahiError: %s", error)
1153
logger.critical(u"AvahiError: %s" + unicode(error))
1242
1155
except KeyboardInterrupt:
1245
logger.debug("Server received KeyboardInterrupt")
1246
logger.debug("Server exiting")
1248
1159
if __name__ == '__main__':