61
61
from dbus.mainloop.glib import DBusGMainLoop
65
66
logger = logging.Logger('mandos')
66
67
syslogger = logging.handlers.SysLogHandler\
67
(facility = logging.handlers.SysLogHandler.LOG_DAEMON)
68
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
68
70
syslogger.setFormatter(logging.Formatter\
69
('%(levelname)s: %(message)s'))
71
('Mandos: %(levelname)s: %(message)s'))
70
72
logger.addHandler(syslogger)
74
console = logging.StreamHandler()
75
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
77
logger.addHandler(console)
74
79
class AvahiError(Exception):
75
80
def __init__(self, value):
103
108
def __init__(self, interface = avahi.IF_UNSPEC, name = None,
104
109
type = None, port = None, TXT = None, domain = "",
105
host = "", max_renames = 12):
110
host = "", max_renames = 32768):
106
111
self.interface = interface
114
119
self.domain = domain
116
121
self.rename_count = 0
122
self.max_renames = max_renames
117
123
def rename(self):
118
124
"""Derived from the Avahi example code"""
119
125
if self.rename_count >= self.max_renames:
120
126
logger.critical(u"No suitable service name found after %i"
121
127
u" retries, exiting.", rename_count)
122
128
raise AvahiServiceError("Too many renames")
123
name = server.GetAlternativeServiceName(name)
124
logger.error(u"Changing name to %r ...", name)
129
self.name = server.GetAlternativeServiceName(self.name)
130
logger.info(u"Changing name to %r ...", str(self.name))
131
syslogger.setFormatter(logging.Formatter\
132
('Mandos (%s): %%(levelname)s:'
133
' %%(message)s' % self.name))
127
136
self.rename_count += 1
163
172
fingerprint: string (40 or 32 hexadecimal digits); used to
164
173
uniquely identify the client
165
174
secret: bytestring; sent verbatim (over TLS) to client
166
fqdn: string (FQDN); available for use by the checker command
175
host: string; available for use by the checker command
167
176
created: datetime.datetime(); object creation, not client host
168
177
last_checked_ok: datetime.datetime() or None if not yet checked OK
169
178
timeout: datetime.timedelta(); How long from last_checked_ok
231
240
raise TypeError(u"No secret or secfile for client %s"
233
self.fqdn = config.get("fqdn", "")
242
self.host = config.get("host", "")
234
243
self.created = datetime.datetime.now()
235
244
self.last_checked_ok = None
236
245
self.timeout = string_to_delta(config["timeout"])
259
268
The possibility that a client might be restarted is left open,
260
269
but not currently used."""
261
270
# If this client doesn't have a secret, it is already stopped.
271
if hasattr(self, "secret") and self.secret:
263
272
logger.info(u"Stopping client %s", self.name)
264
273
self.secret = None
313
322
if self.checker is None:
315
324
# In case check_command has exactly one % operator
316
command = self.check_command % self.fqdn
325
command = self.check_command % self.host
317
326
except TypeError:
318
327
# Escape attributes for the shell
319
328
escaped_attrs = dict((key, re.escape(str(val)))
329
338
logger.info(u"Starting checker %r for %s",
330
339
command, self.name)
340
# We don't need to redirect stdout and stderr, since
341
# in normal mode, that is already done by daemon(),
342
# and in debug mode we don't want to. (Stdin is
343
# always replaced by /dev/null.)
331
344
self.checker = subprocess.Popen(command,
333
346
shell=True, cwd="/")
334
347
self.checker_callback_tag = gobject.child_watch_add\
335
348
(self.checker.pid,
336
349
self.checker_callback)
337
except subprocess.OSError, error:
350
except OSError, error:
338
351
logger.error(u"Failed to start subprocess: %s",
340
353
# Re-run this periodically if run by gobject.timeout_add
346
359
self.checker_callback_tag = None
347
360
if getattr(self, "checker", None) is None:
349
logger.debug("Stopping checker for %(name)s", vars(self))
362
logger.debug(u"Stopping checker for %(name)s", vars(self))
351
364
os.kill(self.checker.pid, signal.SIGTERM)
554
567
datetime.timedelta(1)
555
568
>>> string_to_delta(u'1w')
556
569
datetime.timedelta(7)
570
>>> string_to_delta('5m 30s')
571
datetime.timedelta(0, 330)
559
suffix=unicode(interval[-1])
560
value=int(interval[:-1])
562
delta = datetime.timedelta(value)
564
delta = datetime.timedelta(0, value)
566
delta = datetime.timedelta(0, 0, 0, 0, value)
568
delta = datetime.timedelta(0, 0, 0, 0, 0, value)
570
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
573
timevalue = datetime.timedelta(0)
574
for s in interval.split():
576
suffix=unicode(s[-1])
579
delta = datetime.timedelta(value)
581
delta = datetime.timedelta(0, value)
583
delta = datetime.timedelta(0, 0, 0, 0, value)
585
delta = datetime.timedelta(0, 0, 0, 0, 0, value)
587
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
590
except (ValueError, IndexError):
573
except (ValueError, IndexError):
578
596
def server_state_changed(state):
650
668
global main_loop_started
651
669
main_loop_started = False
653
parser = OptionParser()
671
parser = OptionParser(version = "%%prog %s" % version)
654
672
parser.add_option("-i", "--interface", type="string",
655
673
metavar="IF", help="Bind to interface IF")
656
674
parser.add_option("-a", "--address", type="string",
691
709
server_config = ConfigParser.SafeConfigParser(server_defaults)
692
710
del server_defaults
693
711
server_config.read(os.path.join(options.configdir, "mandos.conf"))
694
server_section = "server"
695
712
# Convert the SafeConfigParser object to a dict
696
server_settings = dict(server_config.items(server_section))
713
server_settings = server_config.defaults()
697
714
# Use getboolean on the boolean config option
698
715
server_settings["debug"] = server_config.getboolean\
699
(server_section, "debug")
700
717
del server_config
702
719
# Override the settings from the config file with command line
710
727
# Now we have our good server settings in "server_settings"
729
debug = server_settings["debug"]
732
syslogger.setLevel(logging.WARNING)
733
console.setLevel(logging.WARNING)
735
if server_settings["servicename"] != "Mandos":
736
syslogger.setFormatter(logging.Formatter\
737
('Mandos (%s): %%(levelname)s:'
739
% server_settings["servicename"]))
712
741
# Parse config file with clients
713
742
client_defaults = { "timeout": "1h",
714
743
"interval": "5m",
715
"checker": "fping -q -- %%(fqdn)s",
744
"checker": "fping -q -- %(host)s",
717
747
client_config = ConfigParser.SafeConfigParser(client_defaults)
718
748
client_config.read(os.path.join(server_settings["configdir"],
736
766
avahi.DBUS_INTERFACE_SERVER )
737
767
# End of Avahi example code
739
debug = server_settings["debug"]
742
console = logging.StreamHandler()
743
# console.setLevel(logging.DEBUG)
744
console.setFormatter(logging.Formatter\
745
('%(levelname)s: %(message)s'))
746
logger.addHandler(console)
750
770
def remove_from_clients(client):
751
771
clients.remove(client)
759
779
= dict(client_config.items(section)))
760
780
for section in client_config.sections()))
782
logger.critical(u"No clients defined")
786
# Redirect stdin so all checkers get /dev/null
787
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
788
os.dup2(null, sys.stdin.fileno())
793
logger.removeHandler(console)
794
# Close all input and output, do double fork, etc.
797
pidfilename = "/var/run/mandos/mandos.pid"
800
pidfile = open(pidfilename, "w")
801
pidfile.write(str(pid) + "\n")
805
logger.error(u"Could not write %s file with PID %d",
806
pidfilename, os.getpid())
766
809
"Cleanup function; run on exit"
813
856
tcp_server.handle_request\
814
857
(*args[2:], **kwargs) or True)
816
logger.debug("Starting main loop")
859
logger.debug(u"Starting main loop")
817
860
main_loop_started = True
819
862
except AvahiError, error: