/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

* mandos (peer_certificate): Handle NULL pointer from
                             "gnutls_certificate_get_peers" slightly
                             better.
  (TCP_handler.handle): Added some extra debug output.

  (MandosServer.GetAllClients,
  MandosServer.GetAllClientsWithProperties,
  MandosServer.RemoveClient): Added doc string.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
14
# Copyright © 2008,2009 Teddy Hogeborn
 
15
# Copyright © 2008,2009 Björn Påhlsson
15
16
16
17
# This program is free software: you can redistribute it and/or modify
17
18
# it under the terms of the GNU General Public License as published by
24
25
#     GNU General Public License for more details.
25
26
26
27
# You should have received a copy of the GNU General Public License
27
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
28
# along with this program.  If not, see
 
29
# <http://www.gnu.org/licenses/>.
28
30
29
31
# Contact the authors at <mandos@fukt.bsnet.se>.
30
32
31
33
 
32
 
from __future__ import division
 
34
from __future__ import division, with_statement, absolute_import
33
35
 
34
36
import SocketServer
35
37
import socket
36
 
import select
37
 
from optparse import OptionParser
 
38
import optparse
38
39
import datetime
39
40
import errno
40
41
import gnutls.crypto
54
55
import stat
55
56
import logging
56
57
import logging.handlers
 
58
import pwd
 
59
from contextlib import closing
57
60
 
58
61
import dbus
 
62
import dbus.service
59
63
import gobject
60
64
import avahi
61
65
from dbus.mainloop.glib import DBusGMainLoop
62
66
import ctypes
 
67
import ctypes.util
63
68
 
 
69
version = "1.0.5"
64
70
 
65
71
logger = logging.Logger('mandos')
66
 
syslogger = logging.handlers.SysLogHandler\
67
 
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
68
 
             address = "/dev/log")
69
 
syslogger.setFormatter(logging.Formatter\
70
 
                        ('Mandos: %(levelname)s: %(message)s'))
 
72
syslogger = (logging.handlers.SysLogHandler
 
73
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
74
              address = "/dev/log"))
 
75
syslogger.setFormatter(logging.Formatter
 
76
                       ('Mandos: %(levelname)s: %(message)s'))
71
77
logger.addHandler(syslogger)
72
78
 
 
79
console = logging.StreamHandler()
 
80
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
 
81
                                       ' %(message)s'))
 
82
logger.addHandler(console)
73
83
 
74
84
class AvahiError(Exception):
75
 
    def __init__(self, value):
 
85
    def __init__(self, value, *args, **kwargs):
76
86
        self.value = value
77
 
    def __str__(self):
78
 
        return repr(self.value)
 
87
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
88
    def __unicode__(self):
 
89
        return unicode(repr(self.value))
79
90
 
80
91
class AvahiServiceError(AvahiError):
81
92
    pass
101
112
                  a sensible number of times
102
113
    """
103
114
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
104
 
                 type = None, port = None, TXT = None, domain = "",
105
 
                 host = "", max_renames = 32768):
 
115
                 servicetype = None, port = None, TXT = None,
 
116
                 domain = "", host = "", max_renames = 32768):
106
117
        self.interface = interface
107
118
        self.name = name
108
 
        self.type = type
 
119
        self.type = servicetype
109
120
        self.port = port
110
 
        if TXT is None:
111
 
            self.TXT = []
112
 
        else:
113
 
            self.TXT = TXT
 
121
        self.TXT = TXT if TXT is not None else []
114
122
        self.domain = domain
115
123
        self.host = host
116
124
        self.rename_count = 0
 
125
        self.max_renames = max_renames
117
126
    def rename(self):
118
127
        """Derived from the Avahi example code"""
119
128
        if self.rename_count >= self.max_renames:
120
 
            logger.critical(u"No suitable service name found after %i"
121
 
                            u" retries, exiting.", rename_count)
122
 
            raise AvahiServiceError("Too many renames")
123
 
        name = server.GetAlternativeServiceName(name)
124
 
        logger.error(u"Changing name to %r ...", name)
125
 
        syslogger.setFormatter(logging.Formatter\
 
129
            logger.critical(u"No suitable Zeroconf service name found"
 
130
                            u" after %i retries, exiting.",
 
131
                            self.rename_count)
 
132
            raise AvahiServiceError(u"Too many renames")
 
133
        self.name = server.GetAlternativeServiceName(self.name)
 
134
        logger.info(u"Changing Zeroconf service name to %r ...",
 
135
                    str(self.name))
 
136
        syslogger.setFormatter(logging.Formatter
126
137
                               ('Mandos (%s): %%(levelname)s:'
127
 
                               ' %%(message)s' % name))
 
138
                                ' %%(message)s' % self.name))
128
139
        self.remove()
129
140
        self.add()
130
141
        self.rename_count += 1
136
147
        """Derived from the Avahi example code"""
137
148
        global group
138
149
        if group is None:
139
 
            group = dbus.Interface\
140
 
                    (bus.get_object(avahi.DBUS_NAME,
 
150
            group = dbus.Interface(bus.get_object
 
151
                                   (avahi.DBUS_NAME,
141
152
                                    server.EntryGroupNew()),
142
 
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
153
                                   avahi.DBUS_INTERFACE_ENTRY_GROUP)
143
154
            group.connect_to_signal('StateChanged',
144
155
                                    entry_group_state_changed)
145
 
        logger.debug(u"Adding service '%s' of type '%s' ...",
 
156
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
146
157
                     service.name, service.type)
147
158
        group.AddService(
148
159
                self.interface,         # interface
159
170
# End of Avahi example code
160
171
 
161
172
 
162
 
class Client(object):
 
173
def _datetime_to_dbus(dt, variant_level=0):
 
174
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
175
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
176
 
 
177
 
 
178
class Client(dbus.service.Object):
163
179
    """A representation of a client host served by this server.
164
180
    Attributes:
165
 
    name:      string; from the config file, used in log messages
 
181
    name:       string; from the config file, used in log messages and
 
182
                        D-Bus identifiers
166
183
    fingerprint: string (40 or 32 hexadecimal digits); used to
167
184
                 uniquely identify the client
168
 
    secret:    bytestring; sent verbatim (over TLS) to client
169
 
    host:      string; available for use by the checker command
170
 
    created:   datetime.datetime(); object creation, not client host
171
 
    last_checked_ok: datetime.datetime() or None if not yet checked OK
172
 
    timeout:   datetime.timedelta(); How long from last_checked_ok
173
 
                                     until this client is invalid
174
 
    interval:  datetime.timedelta(); How often to start a new checker
175
 
    stop_hook: If set, called by stop() as stop_hook(self)
176
 
    checker:   subprocess.Popen(); a running checker process used
177
 
                                   to see if the client lives.
178
 
                                   'None' if no process is running.
 
185
    secret:     bytestring; sent verbatim (over TLS) to client
 
186
    host:       string; available for use by the checker command
 
187
    created:    datetime.datetime(); (UTC) object creation
 
188
    last_enabled: datetime.datetime(); (UTC)
 
189
    enabled:    bool()
 
190
    last_checked_ok: datetime.datetime(); (UTC) or None
 
191
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
192
                                      until this client is invalid
 
193
    interval:   datetime.timedelta(); How often to start a new checker
 
194
    disable_hook:  If set, called by disable() as disable_hook(self)
 
195
    checker:    subprocess.Popen(); a running checker process used
 
196
                                    to see if the client lives.
 
197
                                    'None' if no process is running.
179
198
    checker_initiator_tag: a gobject event source tag, or None
180
 
    stop_initiator_tag:    - '' -
 
199
    disable_initiator_tag:    - '' -
181
200
    checker_callback_tag:  - '' -
182
201
    checker_command: string; External command which is run to check if
183
202
                     client lives.  %() expansions are done at
184
203
                     runtime with vars(self) as dict, so that for
185
204
                     instance %(name)s can be used in the command.
186
 
    Private attibutes:
187
 
    _timeout: Real variable for 'timeout'
188
 
    _interval: Real variable for 'interval'
189
 
    _timeout_milliseconds: Used when calling gobject.timeout_add()
190
 
    _interval_milliseconds: - '' -
 
205
    use_dbus: bool(); Whether to provide D-Bus interface and signals
 
206
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
191
207
    """
192
 
    def _set_timeout(self, timeout):
193
 
        "Setter function for 'timeout' attribute"
194
 
        self._timeout = timeout
195
 
        self._timeout_milliseconds = ((self.timeout.days
196
 
                                       * 24 * 60 * 60 * 1000)
197
 
                                      + (self.timeout.seconds * 1000)
198
 
                                      + (self.timeout.microseconds
199
 
                                         // 1000))
200
 
    timeout = property(lambda self: self._timeout,
201
 
                       _set_timeout)
202
 
    del _set_timeout
203
 
    def _set_interval(self, interval):
204
 
        "Setter function for 'interval' attribute"
205
 
        self._interval = interval
206
 
        self._interval_milliseconds = ((self.interval.days
207
 
                                        * 24 * 60 * 60 * 1000)
208
 
                                       + (self.interval.seconds
209
 
                                          * 1000)
210
 
                                       + (self.interval.microseconds
211
 
                                          // 1000))
212
 
    interval = property(lambda self: self._interval,
213
 
                        _set_interval)
214
 
    del _set_interval
215
 
    def __init__(self, name = None, stop_hook=None, config={}):
 
208
    def timeout_milliseconds(self):
 
209
        "Return the 'timeout' attribute in milliseconds"
 
210
        return ((self.timeout.days * 24 * 60 * 60 * 1000)
 
211
                + (self.timeout.seconds * 1000)
 
212
                + (self.timeout.microseconds // 1000))
 
213
    
 
214
    def interval_milliseconds(self):
 
215
        "Return the 'interval' attribute in milliseconds"
 
216
        return ((self.interval.days * 24 * 60 * 60 * 1000)
 
217
                + (self.interval.seconds * 1000)
 
218
                + (self.interval.microseconds // 1000))
 
219
    
 
220
    def __init__(self, name = None, disable_hook=None, config=None,
 
221
                 use_dbus=True):
216
222
        """Note: the 'checker' key in 'config' sets the
217
223
        'checker_command' attribute and *not* the 'checker'
218
224
        attribute."""
219
225
        self.name = name
 
226
        if config is None:
 
227
            config = {}
220
228
        logger.debug(u"Creating client %r", self.name)
 
229
        self.use_dbus = False   # During __init__
221
230
        # Uppercase and remove spaces from fingerprint for later
222
231
        # comparison purposes with return value from the fingerprint()
223
232
        # function
224
 
        self.fingerprint = config["fingerprint"].upper()\
225
 
                           .replace(u" ", u"")
 
233
        self.fingerprint = (config["fingerprint"].upper()
 
234
                            .replace(u" ", u""))
226
235
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
227
236
        if "secret" in config:
228
237
            self.secret = config["secret"].decode(u"base64")
229
238
        elif "secfile" in config:
230
 
            sf = open(config["secfile"])
231
 
            self.secret = sf.read()
232
 
            sf.close()
 
239
            with closing(open(os.path.expanduser
 
240
                              (os.path.expandvars
 
241
                               (config["secfile"])))) as secfile:
 
242
                self.secret = secfile.read()
233
243
        else:
234
244
            raise TypeError(u"No secret or secfile for client %s"
235
245
                            % self.name)
236
246
        self.host = config.get("host", "")
237
 
        self.created = datetime.datetime.now()
 
247
        self.created = datetime.datetime.utcnow()
 
248
        self.enabled = False
 
249
        self.last_enabled = None
238
250
        self.last_checked_ok = None
239
251
        self.timeout = string_to_delta(config["timeout"])
240
252
        self.interval = string_to_delta(config["interval"])
241
 
        self.stop_hook = stop_hook
 
253
        self.disable_hook = disable_hook
242
254
        self.checker = None
243
255
        self.checker_initiator_tag = None
244
 
        self.stop_initiator_tag = None
 
256
        self.disable_initiator_tag = None
245
257
        self.checker_callback_tag = None
246
 
        self.check_command = config["checker"]
247
 
    def start(self):
 
258
        self.checker_command = config["checker"]
 
259
        self.last_connect = None
 
260
        # Only now, when this client is initialized, can it show up on
 
261
        # the D-Bus
 
262
        self.use_dbus = use_dbus
 
263
        if self.use_dbus:
 
264
            self.dbus_object_path = (dbus.ObjectPath
 
265
                                     ("/clients/"
 
266
                                      + self.name.replace(".", "_")))
 
267
            dbus.service.Object.__init__(self, bus,
 
268
                                         self.dbus_object_path)
 
269
    
 
270
    def enable(self):
248
271
        """Start this client's checker and timeout hooks"""
 
272
        self.last_enabled = datetime.datetime.utcnow()
249
273
        # Schedule a new checker to be started an 'interval' from now,
250
274
        # and every interval from then on.
251
 
        self.checker_initiator_tag = gobject.timeout_add\
252
 
                                     (self._interval_milliseconds,
253
 
                                      self.start_checker)
 
275
        self.checker_initiator_tag = (gobject.timeout_add
 
276
                                      (self.interval_milliseconds(),
 
277
                                       self.start_checker))
254
278
        # Also start a new checker *right now*.
255
279
        self.start_checker()
256
 
        # Schedule a stop() when 'timeout' has passed
257
 
        self.stop_initiator_tag = gobject.timeout_add\
258
 
                                  (self._timeout_milliseconds,
259
 
                                   self.stop)
260
 
    def stop(self):
261
 
        """Stop this client.
262
 
        The possibility that a client might be restarted is left open,
263
 
        but not currently used."""
264
 
        # If this client doesn't have a secret, it is already stopped.
265
 
        if hasattr(self, "secret") and self.secret:
266
 
            logger.info(u"Stopping client %s", self.name)
267
 
            self.secret = None
268
 
        else:
 
280
        # Schedule a disable() when 'timeout' has passed
 
281
        self.disable_initiator_tag = (gobject.timeout_add
 
282
                                   (self.timeout_milliseconds(),
 
283
                                    self.disable))
 
284
        self.enabled = True
 
285
        if self.use_dbus:
 
286
            # Emit D-Bus signals
 
287
            self.PropertyChanged(dbus.String(u"enabled"),
 
288
                                 dbus.Boolean(True, variant_level=1))
 
289
            self.PropertyChanged(dbus.String(u"last_enabled"),
 
290
                                 (_datetime_to_dbus(self.last_enabled,
 
291
                                                    variant_level=1)))
 
292
    
 
293
    def disable(self):
 
294
        """Disable this client."""
 
295
        if not getattr(self, "enabled", False):
269
296
            return False
270
 
        if getattr(self, "stop_initiator_tag", False):
271
 
            gobject.source_remove(self.stop_initiator_tag)
272
 
            self.stop_initiator_tag = None
 
297
        logger.info(u"Disabling client %s", self.name)
 
298
        if getattr(self, "disable_initiator_tag", False):
 
299
            gobject.source_remove(self.disable_initiator_tag)
 
300
            self.disable_initiator_tag = None
273
301
        if getattr(self, "checker_initiator_tag", False):
274
302
            gobject.source_remove(self.checker_initiator_tag)
275
303
            self.checker_initiator_tag = None
276
304
        self.stop_checker()
277
 
        if self.stop_hook:
278
 
            self.stop_hook(self)
 
305
        if self.disable_hook:
 
306
            self.disable_hook(self)
 
307
        self.enabled = False
 
308
        if self.use_dbus:
 
309
            # Emit D-Bus signal
 
310
            self.PropertyChanged(dbus.String(u"enabled"),
 
311
                                 dbus.Boolean(False, variant_level=1))
279
312
        # Do not run this again if called by a gobject.timeout_add
280
313
        return False
 
314
    
281
315
    def __del__(self):
282
 
        self.stop_hook = None
283
 
        self.stop()
284
 
    def checker_callback(self, pid, condition):
 
316
        self.disable_hook = None
 
317
        self.disable()
 
318
    
 
319
    def checker_callback(self, pid, condition, command):
285
320
        """The checker has completed, so take appropriate actions."""
286
 
        now = datetime.datetime.now()
287
321
        self.checker_callback_tag = None
288
322
        self.checker = None
289
 
        if os.WIFEXITED(condition) \
290
 
               and (os.WEXITSTATUS(condition) == 0):
291
 
            logger.info(u"Checker for %(name)s succeeded",
292
 
                        vars(self))
293
 
            self.last_checked_ok = now
294
 
            gobject.source_remove(self.stop_initiator_tag)
295
 
            self.stop_initiator_tag = gobject.timeout_add\
296
 
                                      (self._timeout_milliseconds,
297
 
                                       self.stop)
298
 
        elif not os.WIFEXITED(condition):
 
323
        if self.use_dbus:
 
324
            # Emit D-Bus signal
 
325
            self.PropertyChanged(dbus.String(u"checker_running"),
 
326
                                 dbus.Boolean(False, variant_level=1))
 
327
        if os.WIFEXITED(condition):
 
328
            exitstatus = os.WEXITSTATUS(condition)
 
329
            if exitstatus == 0:
 
330
                logger.info(u"Checker for %(name)s succeeded",
 
331
                            vars(self))
 
332
                self.checked_ok()
 
333
            else:
 
334
                logger.info(u"Checker for %(name)s failed",
 
335
                            vars(self))
 
336
            if self.use_dbus:
 
337
                # Emit D-Bus signal
 
338
                self.CheckerCompleted(dbus.Int16(exitstatus),
 
339
                                      dbus.Int64(condition),
 
340
                                      dbus.String(command))
 
341
        else:
299
342
            logger.warning(u"Checker for %(name)s crashed?",
300
343
                           vars(self))
301
 
        else:
302
 
            logger.info(u"Checker for %(name)s failed",
303
 
                        vars(self))
 
344
            if self.use_dbus:
 
345
                # Emit D-Bus signal
 
346
                self.CheckerCompleted(dbus.Int16(-1),
 
347
                                      dbus.Int64(condition),
 
348
                                      dbus.String(command))
 
349
    
 
350
    def checked_ok(self):
 
351
        """Bump up the timeout for this client.
 
352
        This should only be called when the client has been seen,
 
353
        alive and well.
 
354
        """
 
355
        self.last_checked_ok = datetime.datetime.utcnow()
 
356
        gobject.source_remove(self.disable_initiator_tag)
 
357
        self.disable_initiator_tag = (gobject.timeout_add
 
358
                                      (self.timeout_milliseconds(),
 
359
                                       self.disable))
 
360
        if self.use_dbus:
 
361
            # Emit D-Bus signal
 
362
            self.PropertyChanged(
 
363
                dbus.String(u"last_checked_ok"),
 
364
                (_datetime_to_dbus(self.last_checked_ok,
 
365
                                   variant_level=1)))
 
366
    
304
367
    def start_checker(self):
305
368
        """Start a new checker subprocess if one is not running.
306
369
        If a checker already exists, leave it running and do
315
378
        # is as it should be.
316
379
        if self.checker is None:
317
380
            try:
318
 
                # In case check_command has exactly one % operator
319
 
                command = self.check_command % self.host
 
381
                # In case checker_command has exactly one % operator
 
382
                command = self.checker_command % self.host
320
383
            except TypeError:
321
384
                # Escape attributes for the shell
322
385
                escaped_attrs = dict((key, re.escape(str(val)))
323
386
                                     for key, val in
324
387
                                     vars(self).iteritems())
325
388
                try:
326
 
                    command = self.check_command % escaped_attrs
 
389
                    command = self.checker_command % escaped_attrs
327
390
                except TypeError, error:
328
391
                    logger.error(u'Could not format string "%s":'
329
 
                                 u' %s', self.check_command, error)
 
392
                                 u' %s', self.checker_command, error)
330
393
                    return True # Try again later
331
394
            try:
332
395
                logger.info(u"Starting checker %r for %s",
333
396
                            command, self.name)
 
397
                # We don't need to redirect stdout and stderr, since
 
398
                # in normal mode, that is already done by daemon(),
 
399
                # and in debug mode we don't want to.  (Stdin is
 
400
                # always replaced by /dev/null.)
334
401
                self.checker = subprocess.Popen(command,
335
402
                                                close_fds=True,
336
403
                                                shell=True, cwd="/")
337
 
                self.checker_callback_tag = gobject.child_watch_add\
338
 
                                            (self.checker.pid,
339
 
                                             self.checker_callback)
340
 
            except subprocess.OSError, error:
 
404
                if self.use_dbus:
 
405
                    # Emit D-Bus signal
 
406
                    self.CheckerStarted(command)
 
407
                    self.PropertyChanged(
 
408
                        dbus.String("checker_running"),
 
409
                        dbus.Boolean(True, variant_level=1))
 
410
                self.checker_callback_tag = (gobject.child_watch_add
 
411
                                             (self.checker.pid,
 
412
                                              self.checker_callback,
 
413
                                              data=command))
 
414
            except OSError, error:
341
415
                logger.error(u"Failed to start subprocess: %s",
342
416
                             error)
343
417
        # Re-run this periodically if run by gobject.timeout_add
344
418
        return True
 
419
    
345
420
    def stop_checker(self):
346
421
        """Force the checker process, if any, to stop."""
347
422
        if self.checker_callback_tag:
359
434
            if error.errno != errno.ESRCH: # No such process
360
435
                raise
361
436
        self.checker = None
 
437
        if self.use_dbus:
 
438
            self.PropertyChanged(dbus.String(u"checker_running"),
 
439
                                 dbus.Boolean(False, variant_level=1))
 
440
    
362
441
    def still_valid(self):
363
442
        """Has the timeout not yet passed for this client?"""
364
 
        now = datetime.datetime.now()
 
443
        if not getattr(self, "enabled", False):
 
444
            return False
 
445
        now = datetime.datetime.utcnow()
365
446
        if self.last_checked_ok is None:
366
447
            return now < (self.created + self.timeout)
367
448
        else:
368
449
            return now < (self.last_checked_ok + self.timeout)
 
450
    
 
451
    ## D-Bus methods & signals
 
452
    _interface = u"se.bsnet.fukt.Mandos.Client"
 
453
    
 
454
    # CheckedOK - method
 
455
    CheckedOK = dbus.service.method(_interface)(checked_ok)
 
456
    CheckedOK.__name__ = "CheckedOK"
 
457
    
 
458
    # CheckerCompleted - signal
 
459
    @dbus.service.signal(_interface, signature="nxs")
 
460
    def CheckerCompleted(self, exitcode, waitstatus, command):
 
461
        "D-Bus signal"
 
462
        pass
 
463
    
 
464
    # CheckerStarted - signal
 
465
    @dbus.service.signal(_interface, signature="s")
 
466
    def CheckerStarted(self, command):
 
467
        "D-Bus signal"
 
468
        pass
 
469
    
 
470
    # GetAllProperties - method
 
471
    @dbus.service.method(_interface, out_signature="a{sv}")
 
472
    def GetAllProperties(self):
 
473
        "D-Bus method"
 
474
        return dbus.Dictionary({
 
475
                dbus.String("name"):
 
476
                    dbus.String(self.name, variant_level=1),
 
477
                dbus.String("fingerprint"):
 
478
                    dbus.String(self.fingerprint, variant_level=1),
 
479
                dbus.String("host"):
 
480
                    dbus.String(self.host, variant_level=1),
 
481
                dbus.String("created"):
 
482
                    _datetime_to_dbus(self.created, variant_level=1),
 
483
                dbus.String("last_enabled"):
 
484
                    (_datetime_to_dbus(self.last_enabled,
 
485
                                       variant_level=1)
 
486
                     if self.last_enabled is not None
 
487
                     else dbus.Boolean(False, variant_level=1)),
 
488
                dbus.String("enabled"):
 
489
                    dbus.Boolean(self.enabled, variant_level=1),
 
490
                dbus.String("last_checked_ok"):
 
491
                    (_datetime_to_dbus(self.last_checked_ok,
 
492
                                       variant_level=1)
 
493
                     if self.last_checked_ok is not None
 
494
                     else dbus.Boolean (False, variant_level=1)),
 
495
                dbus.String("timeout"):
 
496
                    dbus.UInt64(self.timeout_milliseconds(),
 
497
                                variant_level=1),
 
498
                dbus.String("interval"):
 
499
                    dbus.UInt64(self.interval_milliseconds(),
 
500
                                variant_level=1),
 
501
                dbus.String("checker"):
 
502
                    dbus.String(self.checker_command,
 
503
                                variant_level=1),
 
504
                dbus.String("checker_running"):
 
505
                    dbus.Boolean(self.checker is not None,
 
506
                                 variant_level=1),
 
507
                dbus.String("object_path"):
 
508
                    dbus.ObjectPath(self.dbus_object_path,
 
509
                                    variant_level=1)
 
510
                }, signature="sv")
 
511
    
 
512
    # IsStillValid - method
 
513
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
 
514
                    (still_valid))
 
515
    IsStillValid.__name__ = "IsStillValid"
 
516
    
 
517
    # PropertyChanged - signal
 
518
    @dbus.service.signal(_interface, signature="sv")
 
519
    def PropertyChanged(self, property, value):
 
520
        "D-Bus signal"
 
521
        pass
 
522
    
 
523
    # SetChecker - method
 
524
    @dbus.service.method(_interface, in_signature="s")
 
525
    def SetChecker(self, checker):
 
526
        "D-Bus setter method"
 
527
        self.checker_command = checker
 
528
        # Emit D-Bus signal
 
529
        self.PropertyChanged(dbus.String(u"checker"),
 
530
                             dbus.String(self.checker_command,
 
531
                                         variant_level=1))
 
532
    
 
533
    # SetHost - method
 
534
    @dbus.service.method(_interface, in_signature="s")
 
535
    def SetHost(self, host):
 
536
        "D-Bus setter method"
 
537
        self.host = host
 
538
        # Emit D-Bus signal
 
539
        self.PropertyChanged(dbus.String(u"host"),
 
540
                             dbus.String(self.host, variant_level=1))
 
541
    
 
542
    # SetInterval - method
 
543
    @dbus.service.method(_interface, in_signature="t")
 
544
    def SetInterval(self, milliseconds):
 
545
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
546
        # Emit D-Bus signal
 
547
        self.PropertyChanged(dbus.String(u"interval"),
 
548
                             (dbus.UInt64(self.interval_milliseconds(),
 
549
                                          variant_level=1)))
 
550
    
 
551
    # SetSecret - method
 
552
    @dbus.service.method(_interface, in_signature="ay",
 
553
                         byte_arrays=True)
 
554
    def SetSecret(self, secret):
 
555
        "D-Bus setter method"
 
556
        self.secret = str(secret)
 
557
    
 
558
    # SetTimeout - method
 
559
    @dbus.service.method(_interface, in_signature="t")
 
560
    def SetTimeout(self, milliseconds):
 
561
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
562
        # Emit D-Bus signal
 
563
        self.PropertyChanged(dbus.String(u"timeout"),
 
564
                             (dbus.UInt64(self.timeout_milliseconds(),
 
565
                                          variant_level=1)))
 
566
    
 
567
    # Enable - method
 
568
    Enable = dbus.service.method(_interface)(enable)
 
569
    Enable.__name__ = "Enable"
 
570
    
 
571
    # StartChecker - method
 
572
    @dbus.service.method(_interface)
 
573
    def StartChecker(self):
 
574
        "D-Bus method"
 
575
        self.start_checker()
 
576
    
 
577
    # Disable - method
 
578
    @dbus.service.method(_interface)
 
579
    def Disable(self):
 
580
        "D-Bus method"
 
581
        self.disable()
 
582
    
 
583
    # StopChecker - method
 
584
    StopChecker = dbus.service.method(_interface)(stop_checker)
 
585
    StopChecker.__name__ = "StopChecker"
 
586
    
 
587
    del _interface
369
588
 
370
589
 
371
590
def peer_certificate(session):
372
591
    "Return the peer's OpenPGP certificate as a bytestring"
373
592
    # If not an OpenPGP certificate...
374
 
    if gnutls.library.functions.gnutls_certificate_type_get\
375
 
            (session._c_object) \
376
 
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
 
593
    if (gnutls.library.functions
 
594
        .gnutls_certificate_type_get(session._c_object)
 
595
        != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
377
596
        # ...do the normal thing
378
597
        return session.peer_certificate
379
 
    list_size = ctypes.c_uint()
380
 
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
381
 
        (session._c_object, ctypes.byref(list_size))
 
598
    list_size = ctypes.c_uint(1)
 
599
    cert_list = (gnutls.library.functions
 
600
                 .gnutls_certificate_get_peers
 
601
                 (session._c_object, ctypes.byref(list_size)))
 
602
    if not bool(cert_list) and list_size.value != 0:
 
603
        raise gnutls.errors.GNUTLSError("error getting peer"
 
604
                                        " certificate")
382
605
    if list_size.value == 0:
383
606
        return None
384
607
    cert = cert_list[0]
388
611
def fingerprint(openpgp):
389
612
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
390
613
    # New GnuTLS "datum" with the OpenPGP public key
391
 
    datum = gnutls.library.types.gnutls_datum_t\
392
 
        (ctypes.cast(ctypes.c_char_p(openpgp),
393
 
                     ctypes.POINTER(ctypes.c_ubyte)),
394
 
         ctypes.c_uint(len(openpgp)))
 
614
    datum = (gnutls.library.types
 
615
             .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
616
                                         ctypes.POINTER
 
617
                                         (ctypes.c_ubyte)),
 
618
                             ctypes.c_uint(len(openpgp))))
395
619
    # New empty GnuTLS certificate
396
620
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
397
 
    gnutls.library.functions.gnutls_openpgp_crt_init\
398
 
        (ctypes.byref(crt))
 
621
    (gnutls.library.functions
 
622
     .gnutls_openpgp_crt_init(ctypes.byref(crt)))
399
623
    # Import the OpenPGP public key into the certificate
400
 
    gnutls.library.functions.gnutls_openpgp_crt_import\
401
 
                    (crt, ctypes.byref(datum),
402
 
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
624
    (gnutls.library.functions
 
625
     .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
626
                                gnutls.library.constants
 
627
                                .GNUTLS_OPENPGP_FMT_RAW))
 
628
    # Verify the self signature in the key
 
629
    crtverify = ctypes.c_uint()
 
630
    (gnutls.library.functions
 
631
     .gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
 
632
    if crtverify.value != 0:
 
633
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
634
        raise gnutls.errors.CertificateSecurityError("Verify failed")
403
635
    # New buffer for the fingerprint
404
 
    buffer = ctypes.create_string_buffer(20)
405
 
    buffer_length = ctypes.c_size_t()
 
636
    buf = ctypes.create_string_buffer(20)
 
637
    buf_len = ctypes.c_size_t()
406
638
    # Get the fingerprint from the certificate into the buffer
407
 
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
408
 
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
 
639
    (gnutls.library.functions
 
640
     .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
641
                                         ctypes.byref(buf_len)))
409
642
    # Deinit the certificate
410
643
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
411
644
    # Convert the buffer to a Python bytestring
412
 
    fpr = ctypes.string_at(buffer, buffer_length.value)
 
645
    fpr = ctypes.string_at(buf, buf_len.value)
413
646
    # Convert the bytestring to hexadecimal notation
414
647
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
415
648
    return hex_fpr
416
649
 
417
650
 
418
 
class tcp_handler(SocketServer.BaseRequestHandler, object):
 
651
class TCP_handler(SocketServer.BaseRequestHandler, object):
419
652
    """A TCP request handler class.
420
653
    Instantiated by IPv6_TCPServer for each request to handle it.
421
654
    Note: This will run in its own forked process."""
422
655
    
423
656
    def handle(self):
424
657
        logger.info(u"TCP connection from: %s",
425
 
                     unicode(self.client_address))
426
 
        session = gnutls.connection.ClientSession\
427
 
                  (self.request, gnutls.connection.X509Credentials())
 
658
                    unicode(self.client_address))
 
659
        session = (gnutls.connection
 
660
                   .ClientSession(self.request,
 
661
                                  gnutls.connection
 
662
                                  .X509Credentials()))
428
663
        
429
664
        line = self.request.makefile().readline()
430
665
        logger.debug(u"Protocol version: %r", line)
443
678
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
444
679
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
445
680
        #                "+DHE-DSS"))
446
 
        priority = "NORMAL"             # Fallback default, since this
447
 
                                        # MUST be set.
448
 
        if self.server.settings["priority"]:
449
 
            priority = self.server.settings["priority"]
450
 
        gnutls.library.functions.gnutls_priority_set_direct\
451
 
            (session._c_object, priority, None);
 
681
        # Use a fallback default, since this MUST be set.
 
682
        priority = self.server.settings.get("priority", "NORMAL")
 
683
        (gnutls.library.functions
 
684
         .gnutls_priority_set_direct(session._c_object,
 
685
                                     priority, None))
452
686
        
453
687
        try:
454
688
            session.handshake()
457
691
            # Do not run session.bye() here: the session is not
458
692
            # established.  Just abandon the request.
459
693
            return
 
694
        logger.debug(u"Handshake succeeded")
460
695
        try:
461
696
            fpr = fingerprint(peer_certificate(session))
462
697
        except (TypeError, gnutls.errors.GNUTLSError), error:
464
699
            session.bye()
465
700
            return
466
701
        logger.debug(u"Fingerprint: %s", fpr)
467
 
        client = None
468
702
        for c in self.server.clients:
469
703
            if c.fingerprint == fpr:
470
704
                client = c
471
705
                break
472
 
        if not client:
 
706
        else:
473
707
            logger.warning(u"Client not found for fingerprint: %s",
474
708
                           fpr)
475
709
            session.bye()
482
716
                           vars(client))
483
717
            session.bye()
484
718
            return
 
719
        ## This won't work here, since we're in a fork.
 
720
        # client.checked_ok()
485
721
        sent_size = 0
486
722
        while sent_size < len(client.secret):
487
723
            sent = session.send(client.secret[sent_size:])
492
728
        session.bye()
493
729
 
494
730
 
495
 
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
 
731
class IPv6_TCPServer(SocketServer.ForkingMixIn,
 
732
                     SocketServer.TCPServer, object):
496
733
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
497
734
    Attributes:
498
735
        settings:       Server settings
499
736
        clients:        Set() of Client objects
 
737
        enabled:        Boolean; whether this server is activated yet
500
738
    """
501
739
    address_family = socket.AF_INET6
502
740
    def __init__(self, *args, **kwargs):
506
744
        if "clients" in kwargs:
507
745
            self.clients = kwargs["clients"]
508
746
            del kwargs["clients"]
509
 
        return super(type(self), self).__init__(*args, **kwargs)
 
747
        self.enabled = False
 
748
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
510
749
    def server_bind(self):
511
750
        """This overrides the normal server_bind() function
512
751
        to bind to an interface if one was specified, and also NOT to
541
780
#                                            if_nametoindex
542
781
#                                            (self.settings
543
782
#                                             ["interface"]))
544
 
            return super(type(self), self).server_bind()
 
783
            return super(IPv6_TCPServer, self).server_bind()
 
784
    def server_activate(self):
 
785
        if self.enabled:
 
786
            return super(IPv6_TCPServer, self).server_activate()
 
787
    def enable(self):
 
788
        self.enabled = True
545
789
 
546
790
 
547
791
def string_to_delta(interval):
557
801
    datetime.timedelta(1)
558
802
    >>> string_to_delta(u'1w')
559
803
    datetime.timedelta(7)
 
804
    >>> string_to_delta('5m 30s')
 
805
    datetime.timedelta(0, 330)
560
806
    """
561
 
    try:
562
 
        suffix=unicode(interval[-1])
563
 
        value=int(interval[:-1])
564
 
        if suffix == u"d":
565
 
            delta = datetime.timedelta(value)
566
 
        elif suffix == u"s":
567
 
            delta = datetime.timedelta(0, value)
568
 
        elif suffix == u"m":
569
 
            delta = datetime.timedelta(0, 0, 0, 0, value)
570
 
        elif suffix == u"h":
571
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, value)
572
 
        elif suffix == u"w":
573
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
574
 
        else:
 
807
    timevalue = datetime.timedelta(0)
 
808
    for s in interval.split():
 
809
        try:
 
810
            suffix = unicode(s[-1])
 
811
            value = int(s[:-1])
 
812
            if suffix == u"d":
 
813
                delta = datetime.timedelta(value)
 
814
            elif suffix == u"s":
 
815
                delta = datetime.timedelta(0, value)
 
816
            elif suffix == u"m":
 
817
                delta = datetime.timedelta(0, 0, 0, 0, value)
 
818
            elif suffix == u"h":
 
819
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
 
820
            elif suffix == u"w":
 
821
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
 
822
            else:
 
823
                raise ValueError
 
824
        except (ValueError, IndexError):
575
825
            raise ValueError
576
 
    except (ValueError, IndexError):
577
 
        raise ValueError
578
 
    return delta
 
826
        timevalue += delta
 
827
    return timevalue
579
828
 
580
829
 
581
830
def server_state_changed(state):
582
831
    """Derived from the Avahi example code"""
583
832
    if state == avahi.SERVER_COLLISION:
584
 
        logger.error(u"Server name collision")
 
833
        logger.error(u"Zeroconf server name collision")
585
834
        service.remove()
586
835
    elif state == avahi.SERVER_RUNNING:
587
836
        service.add()
589
838
 
590
839
def entry_group_state_changed(state, error):
591
840
    """Derived from the Avahi example code"""
592
 
    logger.debug(u"state change: %i", state)
 
841
    logger.debug(u"Avahi state change: %i", state)
593
842
    
594
843
    if state == avahi.ENTRY_GROUP_ESTABLISHED:
595
 
        logger.debug(u"Service established.")
 
844
        logger.debug(u"Zeroconf service established.")
596
845
    elif state == avahi.ENTRY_GROUP_COLLISION:
597
 
        logger.warning(u"Service name collision.")
 
846
        logger.warning(u"Zeroconf service name collision.")
598
847
        service.rename()
599
848
    elif state == avahi.ENTRY_GROUP_FAILURE:
600
 
        logger.critical(u"Error in group state changed %s",
 
849
        logger.critical(u"Avahi: Error in group state changed %s",
601
850
                        unicode(error))
602
 
        raise AvahiGroupError("State changed: %s", str(error))
 
851
        raise AvahiGroupError(u"State changed: %s" % unicode(error))
603
852
 
604
853
def if_nametoindex(interface):
605
854
    """Call the C function if_nametoindex(), or equivalent"""
606
855
    global if_nametoindex
607
856
    try:
608
 
        if "ctypes.util" not in sys.modules:
609
 
            import ctypes.util
610
 
        if_nametoindex = ctypes.cdll.LoadLibrary\
611
 
            (ctypes.util.find_library("c")).if_nametoindex
 
857
        if_nametoindex = (ctypes.cdll.LoadLibrary
 
858
                          (ctypes.util.find_library("c"))
 
859
                          .if_nametoindex)
612
860
    except (OSError, AttributeError):
613
861
        if "struct" not in sys.modules:
614
862
            import struct
617
865
        def if_nametoindex(interface):
618
866
            "Get an interface index the hard way, i.e. using fcntl()"
619
867
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
620
 
            s = socket.socket()
621
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
622
 
                                struct.pack("16s16x", interface))
623
 
            s.close()
 
868
            with closing(socket.socket()) as s:
 
869
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
870
                                    struct.pack("16s16x", interface))
624
871
            interface_index = struct.unpack("I", ifreq[16:20])[0]
625
872
            return interface_index
626
873
    return if_nametoindex(interface)
650
897
 
651
898
 
652
899
def main():
653
 
    global main_loop_started
654
 
    main_loop_started = False
655
 
    
656
 
    parser = OptionParser()
 
900
    parser = optparse.OptionParser(version = "%%prog %s" % version)
657
901
    parser.add_option("-i", "--interface", type="string",
658
902
                      metavar="IF", help="Bind to interface IF")
659
903
    parser.add_option("-a", "--address", type="string",
660
904
                      help="Address to listen for requests on")
661
905
    parser.add_option("-p", "--port", type="int",
662
906
                      help="Port number to receive requests on")
663
 
    parser.add_option("--check", action="store_true", default=False,
 
907
    parser.add_option("--check", action="store_true",
664
908
                      help="Run self-test")
665
909
    parser.add_option("--debug", action="store_true",
666
910
                      help="Debug mode; run in foreground and log to"
673
917
                      default="/etc/mandos", metavar="DIR",
674
918
                      help="Directory to search for configuration"
675
919
                      " files")
676
 
    (options, args) = parser.parse_args()
 
920
    parser.add_option("--no-dbus", action="store_false",
 
921
                      dest="use_dbus",
 
922
                      help="Do not provide D-Bus system bus"
 
923
                      " interface")
 
924
    options = parser.parse_args()[0]
677
925
    
678
926
    if options.check:
679
927
        import doctest
688
936
                        "priority":
689
937
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
690
938
                        "servicename": "Mandos",
 
939
                        "use_dbus": "True",
691
940
                        }
692
941
    
693
942
    # Parse config file for server-global settings
694
943
    server_config = ConfigParser.SafeConfigParser(server_defaults)
695
944
    del server_defaults
696
945
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
697
 
    server_section = "server"
698
946
    # Convert the SafeConfigParser object to a dict
699
 
    server_settings = dict(server_config.items(server_section))
700
 
    # Use getboolean on the boolean config option
701
 
    server_settings["debug"] = server_config.getboolean\
702
 
                               (server_section, "debug")
 
947
    server_settings = server_config.defaults()
 
948
    # Use the appropriate methods on the non-string config options
 
949
    server_settings["debug"] = server_config.getboolean("DEFAULT",
 
950
                                                        "debug")
 
951
    server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
 
952
                                                           "use_dbus")
 
953
    if server_settings["port"]:
 
954
        server_settings["port"] = server_config.getint("DEFAULT",
 
955
                                                       "port")
703
956
    del server_config
704
957
    
705
958
    # Override the settings from the config file with command line
706
959
    # options, if set.
707
960
    for option in ("interface", "address", "port", "debug",
708
 
                   "priority", "servicename", "configdir"):
 
961
                   "priority", "servicename", "configdir",
 
962
                   "use_dbus"):
709
963
        value = getattr(options, option)
710
964
        if value is not None:
711
965
            server_settings[option] = value
712
966
    del options
713
967
    # Now we have our good server settings in "server_settings"
714
968
    
 
969
    # For convenience
715
970
    debug = server_settings["debug"]
 
971
    use_dbus = server_settings["use_dbus"]
716
972
    
717
973
    if not debug:
718
974
        syslogger.setLevel(logging.WARNING)
 
975
        console.setLevel(logging.WARNING)
719
976
    
720
977
    if server_settings["servicename"] != "Mandos":
721
 
        syslogger.setFormatter(logging.Formatter\
 
978
        syslogger.setFormatter(logging.Formatter
722
979
                               ('Mandos (%s): %%(levelname)s:'
723
980
                                ' %%(message)s'
724
981
                                % server_settings["servicename"]))
727
984
    client_defaults = { "timeout": "1h",
728
985
                        "interval": "5m",
729
986
                        "checker": "fping -q -- %%(host)s",
 
987
                        "host": "",
730
988
                        }
731
989
    client_config = ConfigParser.SafeConfigParser(client_defaults)
732
990
    client_config.read(os.path.join(server_settings["configdir"],
733
991
                                    "clients.conf"))
734
992
    
 
993
    clients = Set()
 
994
    tcp_server = IPv6_TCPServer((server_settings["address"],
 
995
                                 server_settings["port"]),
 
996
                                TCP_handler,
 
997
                                settings=server_settings,
 
998
                                clients=clients)
 
999
    pidfilename = "/var/run/mandos.pid"
 
1000
    try:
 
1001
        pidfile = open(pidfilename, "w")
 
1002
    except IOError, error:
 
1003
        logger.error("Could not open file %r", pidfilename)
 
1004
    
 
1005
    try:
 
1006
        uid = pwd.getpwnam("_mandos").pw_uid
 
1007
        gid = pwd.getpwnam("_mandos").pw_gid
 
1008
    except KeyError:
 
1009
        try:
 
1010
            uid = pwd.getpwnam("mandos").pw_uid
 
1011
            gid = pwd.getpwnam("mandos").pw_gid
 
1012
        except KeyError:
 
1013
            try:
 
1014
                uid = pwd.getpwnam("nobody").pw_uid
 
1015
                gid = pwd.getpwnam("nogroup").pw_gid
 
1016
            except KeyError:
 
1017
                uid = 65534
 
1018
                gid = 65534
 
1019
    try:
 
1020
        os.setuid(uid)
 
1021
        os.setgid(gid)
 
1022
    except OSError, error:
 
1023
        if error[0] != errno.EPERM:
 
1024
            raise error
 
1025
    
735
1026
    global service
736
1027
    service = AvahiService(name = server_settings["servicename"],
737
 
                           type = "_mandos._tcp", );
 
1028
                           servicetype = "_mandos._tcp", )
738
1029
    if server_settings["interface"]:
739
 
        service.interface = if_nametoindex(server_settings["interface"])
 
1030
        service.interface = (if_nametoindex
 
1031
                             (server_settings["interface"]))
740
1032
    
741
1033
    global main_loop
742
1034
    global bus
745
1037
    DBusGMainLoop(set_as_default=True )
746
1038
    main_loop = gobject.MainLoop()
747
1039
    bus = dbus.SystemBus()
748
 
    server = dbus.Interface(
749
 
            bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ),
750
 
            avahi.DBUS_INTERFACE_SERVER )
 
1040
    server = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
 
1041
                                           avahi.DBUS_PATH_SERVER),
 
1042
                            avahi.DBUS_INTERFACE_SERVER)
751
1043
    # End of Avahi example code
752
 
    
753
 
    if debug:
754
 
        console = logging.StreamHandler()
755
 
        # console.setLevel(logging.DEBUG)
756
 
        console.setFormatter(logging.Formatter\
757
 
                             ('%(levelname)s: %(message)s'))
758
 
        logger.addHandler(console)
759
 
        del console
760
 
    
761
 
    clients = Set()
762
 
    def remove_from_clients(client):
763
 
        clients.remove(client)
764
 
        if not clients:
765
 
            logger.critical(u"No clients left, exiting")
766
 
            sys.exit()
 
1044
    if use_dbus:
 
1045
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
767
1046
    
768
1047
    clients.update(Set(Client(name = section,
769
 
                              stop_hook = remove_from_clients,
770
1048
                              config
771
 
                              = dict(client_config.items(section)))
 
1049
                              = dict(client_config.items(section)),
 
1050
                              use_dbus = use_dbus)
772
1051
                       for section in client_config.sections()))
773
1052
    if not clients:
774
 
        logger.critical(u"No clients defined")
775
 
        sys.exit(1)
 
1053
        logger.warning(u"No clients defined")
776
1054
    
777
 
    if not debug:
 
1055
    if debug:
 
1056
        # Redirect stdin so all checkers get /dev/null
 
1057
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
1058
        os.dup2(null, sys.stdin.fileno())
 
1059
        if null > 2:
 
1060
            os.close(null)
 
1061
    else:
 
1062
        # No console logging
 
1063
        logger.removeHandler(console)
 
1064
        # Close all input and output, do double fork, etc.
778
1065
        daemon()
779
1066
    
780
 
    pidfilename = "/var/run/mandos/mandos.pid"
781
 
    pid = os.getpid()
782
1067
    try:
783
 
        pidfile = open(pidfilename, "w")
 
1068
        pid = os.getpid()
784
1069
        pidfile.write(str(pid) + "\n")
785
1070
        pidfile.close()
786
1071
        del pidfile
787
 
    except IOError, err:
788
 
        logger.error(u"Could not write %s file with PID %d",
789
 
                     pidfilename, os.getpid())
 
1072
    except IOError:
 
1073
        logger.error(u"Could not write to file %r with PID %d",
 
1074
                     pidfilename, pid)
 
1075
    except NameError:
 
1076
        # "pidfile" was never created
 
1077
        pass
 
1078
    del pidfilename
790
1079
    
791
1080
    def cleanup():
792
1081
        "Cleanup function; run on exit"
799
1088
        
800
1089
        while clients:
801
1090
            client = clients.pop()
802
 
            client.stop_hook = None
803
 
            client.stop()
 
1091
            client.disable_hook = None
 
1092
            client.disable()
804
1093
    
805
1094
    atexit.register(cleanup)
806
1095
    
809
1098
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
810
1099
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
811
1100
    
 
1101
    if use_dbus:
 
1102
        class MandosServer(dbus.service.Object):
 
1103
            """A D-Bus proxy object"""
 
1104
            def __init__(self):
 
1105
                dbus.service.Object.__init__(self, bus, "/")
 
1106
            _interface = u"se.bsnet.fukt.Mandos"
 
1107
            
 
1108
            @dbus.service.signal(_interface, signature="oa{sv}")
 
1109
            def ClientAdded(self, objpath, properties):
 
1110
                "D-Bus signal"
 
1111
                pass
 
1112
            
 
1113
            @dbus.service.signal(_interface, signature="os")
 
1114
            def ClientRemoved(self, objpath, name):
 
1115
                "D-Bus signal"
 
1116
                pass
 
1117
            
 
1118
            @dbus.service.method(_interface, out_signature="ao")
 
1119
            def GetAllClients(self):
 
1120
                "D-Bus method"
 
1121
                return dbus.Array(c.dbus_object_path for c in clients)
 
1122
            
 
1123
            @dbus.service.method(_interface, out_signature="a{oa{sv}}")
 
1124
            def GetAllClientsWithProperties(self):
 
1125
                "D-Bus method"
 
1126
                return dbus.Dictionary(
 
1127
                    ((c.dbus_object_path, c.GetAllProperties())
 
1128
                     for c in clients),
 
1129
                    signature="oa{sv}")
 
1130
            
 
1131
            @dbus.service.method(_interface, in_signature="o")
 
1132
            def RemoveClient(self, object_path):
 
1133
                "D-Bus method"
 
1134
                for c in clients:
 
1135
                    if c.dbus_object_path == object_path:
 
1136
                        clients.remove(c)
 
1137
                        # Don't signal anything except ClientRemoved
 
1138
                        c.use_dbus = False
 
1139
                        c.disable()
 
1140
                        # Emit D-Bus signal
 
1141
                        self.ClientRemoved(object_path, c.name)
 
1142
                        return
 
1143
                raise KeyError
 
1144
            
 
1145
            del _interface
 
1146
        
 
1147
        mandos_server = MandosServer()
 
1148
    
812
1149
    for client in clients:
813
 
        client.start()
814
 
    
815
 
    tcp_server = IPv6_TCPServer((server_settings["address"],
816
 
                                 server_settings["port"]),
817
 
                                tcp_handler,
818
 
                                settings=server_settings,
819
 
                                clients=clients)
 
1150
        if use_dbus:
 
1151
            # Emit D-Bus signal
 
1152
            mandos_server.ClientAdded(client.dbus_object_path,
 
1153
                                      client.GetAllProperties())
 
1154
        client.enable()
 
1155
    
 
1156
    tcp_server.enable()
 
1157
    tcp_server.server_activate()
 
1158
    
820
1159
    # Find out what port we got
821
1160
    service.port = tcp_server.socket.getsockname()[1]
822
1161
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
836
1175
        
837
1176
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
838
1177
                             lambda *args, **kwargs:
839
 
                             tcp_server.handle_request\
840
 
                             (*args[2:], **kwargs) or True)
 
1178
                             (tcp_server.handle_request
 
1179
                              (*args[2:], **kwargs) or True))
841
1180
        
842
1181
        logger.debug(u"Starting main loop")
843
 
        main_loop_started = True
844
1182
        main_loop.run()
845
1183
    except AvahiError, error:
846
 
        logger.critical(u"AvahiError: %s" + unicode(error))
 
1184
        logger.critical(u"AvahiError: %s", error)
847
1185
        sys.exit(1)
848
1186
    except KeyboardInterrupt:
849
1187
        if debug: