/mandos/trunk

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

« back to all changes in this revision

Viewing changes to server.py

  • Committer: Björn Påhlsson
  • Date: 2007-10-20 21:38:25 UTC
  • Revision ID: belorn@tower-20071020213825-abf6f0d1c33ee961
First working version with: IPv6, GnuTLS, X.509 certificates, DN
retrieval.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8 -*-
3
 
4
 
# Mandos server - give out binary blobs to connecting clients.
5
 
6
 
# This program is partly derived from an example program for an Avahi
7
 
# service publisher, downloaded from
8
 
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
9
 
# following functions: "AvahiService.add", "AvahiService.remove",
10
 
# "server_state_changed", "entry_group_state_changed", and some lines
11
 
# in "main".
12
 
13
 
# Everything else is
14
 
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
15
 
16
 
# This program is free software: you can redistribute it and/or modify
17
 
# it under the terms of the GNU General Public License as published by
18
 
# the Free Software Foundation, either version 3 of the License, or
19
 
# (at your option) any later version.
20
 
#
21
 
#     This program is distributed in the hope that it will be useful,
22
 
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 
#     GNU General Public License for more details.
25
 
26
 
# 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
 
29
 
# Contact the authors at <mandos@fukt.bsnet.se>.
30
 
31
 
 
32
 
from __future__ import division
33
 
 
34
 
import SocketServer
35
 
import socket
36
 
import select
37
 
from optparse import OptionParser
38
 
import datetime
39
 
import errno
40
 
import gnutls.crypto
41
 
import gnutls.connection
42
 
import gnutls.errors
43
 
import gnutls.library.functions
44
 
import gnutls.library.constants
45
 
import gnutls.library.types
46
 
import ConfigParser
47
 
import sys
48
 
import re
49
 
import os
50
 
import signal
51
 
from sets import Set
52
 
import subprocess
53
 
import atexit
54
 
import stat
55
 
import logging
56
 
import logging.handlers
57
 
 
58
 
import dbus
59
 
import gobject
60
 
import avahi
61
 
from dbus.mainloop.glib import DBusGMainLoop
62
 
import ctypes
63
 
 
64
 
# Brief description of the operation of this program:
65
 
66
 
# This server announces itself as a Zeroconf service.  Connecting
67
 
# clients use the TLS protocol, with the unusual quirk that this
68
 
# server program acts as a TLS "client" while a connecting client acts
69
 
# as a TLS "server".  The client (acting as a TLS "server") must
70
 
# supply an OpenPGP certificate, and the fingerprint of this
71
 
# certificate is used by this server to look up (in a list read from a
72
 
# file at start time) which binary blob to give the client.  No other
73
 
# authentication or authorization is done by this server.
74
 
 
75
 
 
76
 
logger = logging.Logger('mandos')
77
 
syslogger = logging.handlers.SysLogHandler\
78
 
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON)
79
 
syslogger.setFormatter(logging.Formatter\
80
 
                        ('%(levelname)s: %(message)s'))
81
 
logger.addHandler(syslogger)
82
 
del syslogger
83
 
 
84
 
 
85
 
class AvahiError(Exception):
86
 
    def __init__(self, value):
87
 
        self.value = value
88
 
    def __str__(self):
89
 
        return repr(self.value)
90
 
 
91
 
class AvahiServiceError(AvahiError):
92
 
    pass
93
 
 
94
 
class AvahiGroupError(AvahiError):
95
 
    pass
96
 
 
97
 
 
98
 
class AvahiService(object):
99
 
    """An Avahi (Zeroconf) service.
100
 
    Attributes:
101
 
    interface: integer; avahi.IF_UNSPEC or an interface index.
102
 
               Used to optionally bind to the specified interface.
103
 
    name: string; Example: 'Mandos'
104
 
    type: string; Example: '_mandos._tcp'.
105
 
                  See <http://www.dns-sd.org/ServiceTypes.html>
106
 
    port: integer; what port to announce
107
 
    TXT: list of strings; TXT record for the service
108
 
    domain: string; Domain to publish on, default to .local if empty.
109
 
    host: string; Host to publish records for, default is localhost
110
 
    max_renames: integer; maximum number of renames
111
 
    rename_count: integer; counter so we only rename after collisions
112
 
                  a sensible number of times
113
 
    """
114
 
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
 
                 type = None, port = None, TXT = None, domain = "",
116
 
                 host = "", max_renames = 12):
117
 
        self.interface = interface
118
 
        self.name = name
119
 
        self.type = type
120
 
        self.port = port
121
 
        if TXT is None:
122
 
            self.TXT = []
123
 
        else:
124
 
            self.TXT = TXT
125
 
        self.domain = domain
126
 
        self.host = host
127
 
        self.rename_count = 0
128
 
    def rename(self):
129
 
        """Derived from the Avahi example code"""
130
 
        if self.rename_count >= self.max_renames:
131
 
            logger.critical(u"No suitable service name found after %i"
132
 
                            u" retries, exiting.", rename_count)
133
 
            raise AvahiServiceError("Too many renames")
134
 
        name = server.GetAlternativeServiceName(name)
135
 
        logger.error(u"Changing name to %r ...", name)
136
 
        self.remove()
137
 
        self.add()
138
 
        self.rename_count += 1
139
 
    def remove(self):
140
 
        """Derived from the Avahi example code"""
141
 
        if group is not None:
142
 
            group.Reset()
143
 
    def add(self):
144
 
        """Derived from the Avahi example code"""
145
 
        global group
146
 
        if group is None:
147
 
            group = dbus.Interface\
148
 
                    (bus.get_object(avahi.DBUS_NAME,
149
 
                                    server.EntryGroupNew()),
150
 
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
151
 
            group.connect_to_signal('StateChanged',
152
 
                                    entry_group_state_changed)
153
 
        logger.debug(u"Adding service '%s' of type '%s' ...",
154
 
                     service.name, service.type)
155
 
        group.AddService(
156
 
                self.interface,         # interface
157
 
                avahi.PROTO_INET6,      # protocol
158
 
                dbus.UInt32(0),         # flags
159
 
                self.name, self.type,
160
 
                self.domain, self.host,
161
 
                dbus.UInt16(self.port),
162
 
                avahi.string_array_to_txt_array(self.TXT))
163
 
        group.Commit()
164
 
 
165
 
# From the Avahi example code:
166
 
group = None                            # our entry group
167
 
# End of Avahi example code
168
 
 
169
 
 
170
 
class Client(object):
171
 
    """A representation of a client host served by this server.
172
 
    Attributes:
173
 
    name:      string; from the config file, used in log messages
174
 
    fingerprint: string (40 or 32 hexadecimal digits); used to
175
 
                 uniquely identify the client
176
 
    secret:    bytestring; sent verbatim (over TLS) to client
177
 
    fqdn:      string (FQDN); available for use by the checker command
178
 
    created:   datetime.datetime(); object creation, not client host
179
 
    last_checked_ok: datetime.datetime() or None if not yet checked OK
180
 
    timeout:   datetime.timedelta(); How long from last_checked_ok
181
 
                                     until this client is invalid
182
 
    interval:  datetime.timedelta(); How often to start a new checker
183
 
    stop_hook: If set, called by stop() as stop_hook(self)
184
 
    checker:   subprocess.Popen(); a running checker process used
185
 
                                   to see if the client lives.
186
 
                                   'None' if no process is running.
187
 
    checker_initiator_tag: a gobject event source tag, or None
188
 
    stop_initiator_tag:    - '' -
189
 
    checker_callback_tag:  - '' -
190
 
    checker_command: string; External command which is run to check if
191
 
                     client lives.  %() expansions are done at
192
 
                     runtime with vars(self) as dict, so that for
193
 
                     instance %(name)s can be used in the command.
194
 
    Private attibutes:
195
 
    _timeout: Real variable for 'timeout'
196
 
    _interval: Real variable for 'interval'
197
 
    _timeout_milliseconds: Used when calling gobject.timeout_add()
198
 
    _interval_milliseconds: - '' -
199
 
    """
200
 
    def _set_timeout(self, timeout):
201
 
        "Setter function for 'timeout' attribute"
202
 
        self._timeout = timeout
203
 
        self._timeout_milliseconds = ((self.timeout.days
204
 
                                       * 24 * 60 * 60 * 1000)
205
 
                                      + (self.timeout.seconds * 1000)
206
 
                                      + (self.timeout.microseconds
207
 
                                         // 1000))
208
 
    timeout = property(lambda self: self._timeout,
209
 
                       _set_timeout)
210
 
    del _set_timeout
211
 
    def _set_interval(self, interval):
212
 
        "Setter function for 'interval' attribute"
213
 
        self._interval = interval
214
 
        self._interval_milliseconds = ((self.interval.days
215
 
                                        * 24 * 60 * 60 * 1000)
216
 
                                       + (self.interval.seconds
217
 
                                          * 1000)
218
 
                                       + (self.interval.microseconds
219
 
                                          // 1000))
220
 
    interval = property(lambda self: self._interval,
221
 
                        _set_interval)
222
 
    del _set_interval
223
 
    def __init__(self, name = None, stop_hook=None, config={}):
224
 
        """Note: the 'checker' key in 'config' sets the
225
 
        'checker_command' attribute and *not* the 'checker'
226
 
        attribute."""
227
 
        self.name = name
228
 
        logger.debug(u"Creating client %r", self.name)
229
 
        # Uppercase and remove spaces from fingerprint for later
230
 
        # comparison purposes with return value from the fingerprint()
231
 
        # function
232
 
        self.fingerprint = config["fingerprint"].upper()\
233
 
                           .replace(u" ", u"")
234
 
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
235
 
        if "secret" in config:
236
 
            self.secret = config["secret"].decode(u"base64")
237
 
        elif "secfile" in config:
238
 
            sf = open(config["secfile"])
239
 
            self.secret = sf.read()
240
 
            sf.close()
241
 
        else:
242
 
            raise TypeError(u"No secret or secfile for client %s"
243
 
                            % self.name)
244
 
        self.fqdn = config.get("fqdn", "")
245
 
        self.created = datetime.datetime.now()
246
 
        self.last_checked_ok = None
247
 
        self.timeout = string_to_delta(config["timeout"])
248
 
        self.interval = string_to_delta(config["interval"])
249
 
        self.stop_hook = stop_hook
250
 
        self.checker = None
251
 
        self.checker_initiator_tag = None
252
 
        self.stop_initiator_tag = None
253
 
        self.checker_callback_tag = None
254
 
        self.check_command = config["checker"]
255
 
    def start(self):
256
 
        """Start this client's checker and timeout hooks"""
257
 
        # Schedule a new checker to be started an 'interval' from now,
258
 
        # and every interval from then on.
259
 
        self.checker_initiator_tag = gobject.timeout_add\
260
 
                                     (self._interval_milliseconds,
261
 
                                      self.start_checker)
262
 
        # Also start a new checker *right now*.
263
 
        self.start_checker()
264
 
        # Schedule a stop() when 'timeout' has passed
265
 
        self.stop_initiator_tag = gobject.timeout_add\
266
 
                                  (self._timeout_milliseconds,
267
 
                                   self.stop)
268
 
    def stop(self):
269
 
        """Stop this client.
270
 
        The possibility that a client might be restarted is left open,
271
 
        but not currently used."""
272
 
        # If this client doesn't have a secret, it is already stopped.
273
 
        if self.secret:
274
 
            logger.info(u"Stopping client %s", self.name)
275
 
            self.secret = None
276
 
        else:
277
 
            return False
278
 
        if getattr(self, "stop_initiator_tag", False):
279
 
            gobject.source_remove(self.stop_initiator_tag)
280
 
            self.stop_initiator_tag = None
281
 
        if getattr(self, "checker_initiator_tag", False):
282
 
            gobject.source_remove(self.checker_initiator_tag)
283
 
            self.checker_initiator_tag = None
284
 
        self.stop_checker()
285
 
        if self.stop_hook:
286
 
            self.stop_hook(self)
287
 
        # Do not run this again if called by a gobject.timeout_add
288
 
        return False
289
 
    def __del__(self):
290
 
        self.stop_hook = None
291
 
        self.stop()
292
 
    def checker_callback(self, pid, condition):
293
 
        """The checker has completed, so take appropriate actions."""
294
 
        now = datetime.datetime.now()
295
 
        self.checker_callback_tag = None
296
 
        self.checker = None
297
 
        if os.WIFEXITED(condition) \
298
 
               and (os.WEXITSTATUS(condition) == 0):
299
 
            logger.info(u"Checker for %(name)s succeeded",
300
 
                        vars(self))
301
 
            self.last_checked_ok = now
302
 
            gobject.source_remove(self.stop_initiator_tag)
303
 
            self.stop_initiator_tag = gobject.timeout_add\
304
 
                                      (self._timeout_milliseconds,
305
 
                                       self.stop)
306
 
        elif not os.WIFEXITED(condition):
307
 
            logger.warning(u"Checker for %(name)s crashed?",
308
 
                           vars(self))
309
 
        else:
310
 
            logger.info(u"Checker for %(name)s failed",
311
 
                        vars(self))
312
 
    def start_checker(self):
313
 
        """Start a new checker subprocess if one is not running.
314
 
        If a checker already exists, leave it running and do
315
 
        nothing."""
316
 
        # The reason for not killing a running checker is that if we
317
 
        # did that, then if a checker (for some reason) started
318
 
        # running slowly and taking more than 'interval' time, the
319
 
        # client would inevitably timeout, since no checker would get
320
 
        # a chance to run to completion.  If we instead leave running
321
 
        # checkers alone, the checker would have to take more time
322
 
        # than 'timeout' for the client to be declared invalid, which
323
 
        # is as it should be.
324
 
        if self.checker is None:
325
 
            try:
326
 
                # In case check_command has exactly one % operator
327
 
                command = self.check_command % self.fqdn
328
 
            except TypeError:
329
 
                # Escape attributes for the shell
330
 
                escaped_attrs = dict((key, re.escape(str(val)))
331
 
                                     for key, val in
332
 
                                     vars(self).iteritems())
333
 
                try:
334
 
                    command = self.check_command % escaped_attrs
335
 
                except TypeError, error:
336
 
                    logger.error(u'Could not format string "%s":'
337
 
                                 u' %s', self.check_command, error)
338
 
                    return True # Try again later
339
 
            try:
340
 
                logger.info(u"Starting checker %r for %s",
341
 
                            command, self.name)
342
 
                self.checker = subprocess.Popen(command,
343
 
                                                close_fds=True,
344
 
                                                shell=True, cwd="/")
345
 
                self.checker_callback_tag = gobject.child_watch_add\
346
 
                                            (self.checker.pid,
347
 
                                             self.checker_callback)
348
 
            except subprocess.OSError, error:
349
 
                logger.error(u"Failed to start subprocess: %s",
350
 
                             error)
351
 
        # Re-run this periodically if run by gobject.timeout_add
352
 
        return True
353
 
    def stop_checker(self):
354
 
        """Force the checker process, if any, to stop."""
355
 
        if self.checker_callback_tag:
356
 
            gobject.source_remove(self.checker_callback_tag)
357
 
            self.checker_callback_tag = None
358
 
        if getattr(self, "checker", None) is None:
359
 
            return
360
 
        logger.debug("Stopping checker for %(name)s", vars(self))
361
 
        try:
362
 
            os.kill(self.checker.pid, signal.SIGTERM)
363
 
            #os.sleep(0.5)
364
 
            #if self.checker.poll() is None:
365
 
            #    os.kill(self.checker.pid, signal.SIGKILL)
366
 
        except OSError, error:
367
 
            if error.errno != errno.ESRCH: # No such process
368
 
                raise
369
 
        self.checker = None
370
 
    def still_valid(self):
371
 
        """Has the timeout not yet passed for this client?"""
372
 
        now = datetime.datetime.now()
373
 
        if self.last_checked_ok is None:
374
 
            return now < (self.created + self.timeout)
375
 
        else:
376
 
            return now < (self.last_checked_ok + self.timeout)
377
 
 
378
 
 
379
 
def peer_certificate(session):
380
 
    "Return the peer's OpenPGP certificate as a bytestring"
381
 
    # If not an OpenPGP certificate...
382
 
    if gnutls.library.functions.gnutls_certificate_type_get\
383
 
            (session._c_object) \
384
 
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
385
 
        # ...do the normal thing
386
 
        return session.peer_certificate
387
 
    list_size = ctypes.c_uint()
388
 
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
389
 
        (session._c_object, ctypes.byref(list_size))
390
 
    if list_size.value == 0:
391
 
        return None
392
 
    cert = cert_list[0]
393
 
    return ctypes.string_at(cert.data, cert.size)
394
 
 
395
 
 
396
 
def fingerprint(openpgp):
397
 
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
398
 
    # New GnuTLS "datum" with the OpenPGP public key
399
 
    datum = gnutls.library.types.gnutls_datum_t\
400
 
        (ctypes.cast(ctypes.c_char_p(openpgp),
401
 
                     ctypes.POINTER(ctypes.c_ubyte)),
402
 
         ctypes.c_uint(len(openpgp)))
403
 
    # New empty GnuTLS certificate
404
 
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
405
 
    gnutls.library.functions.gnutls_openpgp_crt_init\
406
 
        (ctypes.byref(crt))
407
 
    # Import the OpenPGP public key into the certificate
408
 
    gnutls.library.functions.gnutls_openpgp_crt_import\
409
 
                    (crt, ctypes.byref(datum),
410
 
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
411
 
    # New buffer for the fingerprint
412
 
    buffer = ctypes.create_string_buffer(20)
413
 
    buffer_length = ctypes.c_size_t()
414
 
    # Get the fingerprint from the certificate into the buffer
415
 
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
416
 
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
417
 
    # Deinit the certificate
418
 
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
419
 
    # Convert the buffer to a Python bytestring
420
 
    fpr = ctypes.string_at(buffer, buffer_length.value)
421
 
    # Convert the bytestring to hexadecimal notation
422
 
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
423
 
    return hex_fpr
424
 
 
425
 
 
426
 
class tcp_handler(SocketServer.BaseRequestHandler, object):
427
 
    """A TCP request handler class.
428
 
    Instantiated by IPv6_TCPServer for each request to handle it.
429
 
    Note: This will run in its own forked process."""
430
 
    
431
 
    def handle(self):
432
 
        logger.info(u"TCP connection from: %s",
433
 
                     unicode(self.client_address))
434
 
        session = gnutls.connection.ClientSession\
435
 
                  (self.request, gnutls.connection.X509Credentials())
436
 
        
437
 
        line = self.request.makefile().readline()
438
 
        logger.debug(u"Protocol version: %r", line)
439
 
        try:
440
 
            if int(line.strip().split()[0]) > 1:
441
 
                raise RuntimeError
442
 
        except (ValueError, IndexError, RuntimeError), error:
443
 
            logger.error(u"Unknown protocol version: %s", error)
444
 
            return
445
 
        
446
 
        # Note: gnutls.connection.X509Credentials is really a generic
447
 
        # GnuTLS certificate credentials object so long as no X.509
448
 
        # keys are added to it.  Therefore, we can use it here despite
449
 
        # using OpenPGP certificates.
450
 
        
451
 
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
452
 
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
453
 
        #                "+DHE-DSS"))
454
 
        priority = "NORMAL"             # Fallback default, since this
455
 
                                        # MUST be set.
456
 
        if self.server.settings["priority"]:
457
 
            priority = self.server.settings["priority"]
458
 
        gnutls.library.functions.gnutls_priority_set_direct\
459
 
            (session._c_object, priority, None);
460
 
        
461
 
        try:
462
 
            session.handshake()
463
 
        except gnutls.errors.GNUTLSError, error:
464
 
            logger.warning(u"Handshake failed: %s", error)
465
 
            # Do not run session.bye() here: the session is not
466
 
            # established.  Just abandon the request.
467
 
            return
468
 
        try:
469
 
            fpr = fingerprint(peer_certificate(session))
470
 
        except (TypeError, gnutls.errors.GNUTLSError), error:
471
 
            logger.warning(u"Bad certificate: %s", error)
472
 
            session.bye()
473
 
            return
474
 
        logger.debug(u"Fingerprint: %s", fpr)
475
 
        client = None
476
 
        for c in self.server.clients:
477
 
            if c.fingerprint == fpr:
478
 
                client = c
479
 
                break
480
 
        if not client:
481
 
            logger.warning(u"Client not found for fingerprint: %s",
482
 
                           fpr)
483
 
            session.bye()
484
 
            return
485
 
        # Have to check if client.still_valid(), since it is possible
486
 
        # that the client timed out while establishing the GnuTLS
487
 
        # session.
488
 
        if not client.still_valid():
489
 
            logger.warning(u"Client %(name)s is invalid",
490
 
                           vars(client))
491
 
            session.bye()
492
 
            return
493
 
        sent_size = 0
494
 
        while sent_size < len(client.secret):
495
 
            sent = session.send(client.secret[sent_size:])
496
 
            logger.debug(u"Sent: %d, remaining: %d",
497
 
                         sent, len(client.secret)
498
 
                         - (sent_size + sent))
499
 
            sent_size += sent
500
 
        session.bye()
501
 
 
502
 
 
503
 
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
504
 
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
505
 
    Attributes:
506
 
        settings:       Server settings
507
 
        clients:        Set() of Client objects
508
 
    """
509
 
    address_family = socket.AF_INET6
510
 
    def __init__(self, *args, **kwargs):
511
 
        if "settings" in kwargs:
512
 
            self.settings = kwargs["settings"]
513
 
            del kwargs["settings"]
514
 
        if "clients" in kwargs:
515
 
            self.clients = kwargs["clients"]
516
 
            del kwargs["clients"]
517
 
        return super(type(self), self).__init__(*args, **kwargs)
518
 
    def server_bind(self):
519
 
        """This overrides the normal server_bind() function
520
 
        to bind to an interface if one was specified, and also NOT to
521
 
        bind to an address or port if they were not specified."""
522
 
        if self.settings["interface"]:
523
 
            # 25 is from /usr/include/asm-i486/socket.h
524
 
            SO_BINDTODEVICE = getattr(socket, "SO_BINDTODEVICE", 25)
525
 
            try:
526
 
                self.socket.setsockopt(socket.SOL_SOCKET,
527
 
                                       SO_BINDTODEVICE,
528
 
                                       self.settings["interface"])
529
 
            except socket.error, error:
530
 
                if error[0] == errno.EPERM:
531
 
                    logger.error(u"No permission to"
532
 
                                 u" bind to interface %s",
533
 
                                 self.settings["interface"])
534
 
                else:
535
 
                    raise error
536
 
        # Only bind(2) the socket if we really need to.
537
 
        if self.server_address[0] or self.server_address[1]:
538
 
            if not self.server_address[0]:
539
 
                in6addr_any = "::"
540
 
                self.server_address = (in6addr_any,
541
 
                                       self.server_address[1])
542
 
            elif self.server_address[1] is None:
543
 
                self.server_address = (self.server_address[0],
544
 
                                       0)
545
 
            return super(type(self), self).server_bind()
546
 
 
547
 
 
548
 
def string_to_delta(interval):
549
 
    """Parse a string and return a datetime.timedelta
550
 
 
551
 
    >>> string_to_delta('7d')
552
 
    datetime.timedelta(7)
553
 
    >>> string_to_delta('60s')
554
 
    datetime.timedelta(0, 60)
555
 
    >>> string_to_delta('60m')
556
 
    datetime.timedelta(0, 3600)
557
 
    >>> string_to_delta('24h')
558
 
    datetime.timedelta(1)
559
 
    >>> string_to_delta(u'1w')
560
 
    datetime.timedelta(7)
561
 
    """
562
 
    try:
563
 
        suffix=unicode(interval[-1])
564
 
        value=int(interval[:-1])
565
 
        if suffix == u"d":
566
 
            delta = datetime.timedelta(value)
567
 
        elif suffix == u"s":
568
 
            delta = datetime.timedelta(0, value)
569
 
        elif suffix == u"m":
570
 
            delta = datetime.timedelta(0, 0, 0, 0, value)
571
 
        elif suffix == u"h":
572
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, value)
573
 
        elif suffix == u"w":
574
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
575
 
        else:
576
 
            raise ValueError
577
 
    except (ValueError, IndexError):
578
 
        raise ValueError
579
 
    return delta
580
 
 
581
 
 
582
 
def server_state_changed(state):
583
 
    """Derived from the Avahi example code"""
584
 
    if state == avahi.SERVER_COLLISION:
585
 
        logger.error(u"Server name collision")
586
 
        service.remove()
587
 
    elif state == avahi.SERVER_RUNNING:
588
 
        service.add()
589
 
 
590
 
 
591
 
def entry_group_state_changed(state, error):
592
 
    """Derived from the Avahi example code"""
593
 
    logger.debug(u"state change: %i", state)
594
 
    
595
 
    if state == avahi.ENTRY_GROUP_ESTABLISHED:
596
 
        logger.debug(u"Service established.")
597
 
    elif state == avahi.ENTRY_GROUP_COLLISION:
598
 
        logger.warning(u"Service name collision.")
599
 
        service.rename()
600
 
    elif state == avahi.ENTRY_GROUP_FAILURE:
601
 
        logger.critical(u"Error in group state changed %s",
602
 
                        unicode(error))
603
 
        raise AvahiGroupError("State changed: %s", str(error))
604
 
 
605
 
def if_nametoindex(interface):
606
 
    """Call the C function if_nametoindex(), or equivalent"""
607
 
    global if_nametoindex
608
 
    try:
609
 
        if "ctypes.util" not in sys.modules:
610
 
            import ctypes.util
611
 
        if_nametoindex = ctypes.cdll.LoadLibrary\
612
 
            (ctypes.util.find_library("c")).if_nametoindex
613
 
    except (OSError, AttributeError):
614
 
        if "struct" not in sys.modules:
615
 
            import struct
616
 
        if "fcntl" not in sys.modules:
617
 
            import fcntl
618
 
        def if_nametoindex(interface):
619
 
            "Get an interface index the hard way, i.e. using fcntl()"
620
 
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
621
 
            s = socket.socket()
622
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
623
 
                                struct.pack("16s16x", interface))
624
 
            s.close()
625
 
            interface_index = struct.unpack("I", ifreq[16:20])[0]
626
 
            return interface_index
627
 
    return if_nametoindex(interface)
628
 
 
629
 
 
630
 
def daemon(nochdir, noclose):
631
 
    """See daemon(3).  Standard BSD Unix function.
632
 
    This should really exist as os.daemon, but it doesn't (yet)."""
633
 
    if os.fork():
634
 
        sys.exit()
635
 
    os.setsid()
636
 
    if not nochdir:
637
 
        os.chdir("/")
638
 
    if not noclose:
639
 
        # Close all standard open file descriptors
640
 
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
641
 
        if not stat.S_ISCHR(os.fstat(null).st_mode):
642
 
            raise OSError(errno.ENODEV,
643
 
                          "/dev/null not a character device")
644
 
        os.dup2(null, sys.stdin.fileno())
645
 
        os.dup2(null, sys.stdout.fileno())
646
 
        os.dup2(null, sys.stderr.fileno())
647
 
        if null > 2:
648
 
            os.close(null)
649
 
 
650
 
 
651
 
def main():
652
 
    global main_loop_started
653
 
    main_loop_started = False
654
 
    
655
 
    parser = OptionParser()
656
 
    parser.add_option("-i", "--interface", type="string",
657
 
                      metavar="IF", help="Bind to interface IF")
658
 
    parser.add_option("-a", "--address", type="string",
659
 
                      help="Address to listen for requests on")
660
 
    parser.add_option("-p", "--port", type="int",
661
 
                      help="Port number to receive requests on")
662
 
    parser.add_option("--check", action="store_true", default=False,
663
 
                      help="Run self-test")
664
 
    parser.add_option("--debug", action="store_true", default=False,
665
 
                      help="Debug mode; run in foreground and log to"
666
 
                      " terminal")
667
 
    parser.add_option("--priority", type="string", help="GnuTLS"
668
 
                      " priority string (see GnuTLS documentation)")
669
 
    parser.add_option("--servicename", type="string", metavar="NAME",
670
 
                      help="Zeroconf service name")
671
 
    parser.add_option("--configdir", type="string",
672
 
                      default="/etc/mandos", metavar="DIR",
673
 
                      help="Directory to search for configuration"
674
 
                      " files")
675
 
    (options, args) = parser.parse_args()
676
 
    
677
 
    if options.check:
678
 
        import doctest
679
 
        doctest.testmod()
680
 
        sys.exit()
681
 
    
682
 
    # Default values for config file for server-global settings
683
 
    server_defaults = { "interface": "",
684
 
                        "address": "",
685
 
                        "port": "",
686
 
                        "debug": "False",
687
 
                        "priority":
688
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
689
 
                        "servicename": "Mandos",
690
 
                        }
691
 
    
692
 
    # Parse config file for server-global settings
693
 
    server_config = ConfigParser.SafeConfigParser(server_defaults)
694
 
    del server_defaults
695
 
    server_config.read(os.path.join(options.configdir, "server.conf"))
696
 
    server_section = "server"
697
 
    # Convert the SafeConfigParser object to a dict
698
 
    server_settings = dict(server_config.items(server_section))
699
 
    # Use getboolean on the boolean config option
700
 
    server_settings["debug"] = server_config.getboolean\
701
 
                               (server_section, "debug")
702
 
    del server_config
703
 
    
704
 
    # Override the settings from the config file with command line
705
 
    # options, if set.
706
 
    for option in ("interface", "address", "port", "debug",
707
 
                   "priority", "servicename", "configdir"):
708
 
        value = getattr(options, option)
709
 
        if value is not None:
710
 
            server_settings[option] = value
711
 
    del options
712
 
    # Now we have our good server settings in "server_settings"
713
 
    
714
 
    # Parse config file with clients
715
 
    client_defaults = { "timeout": "1h",
716
 
                        "interval": "5m",
717
 
                        "checker": "fping -q -- %%(fqdn)s",
718
 
                        }
719
 
    client_config = ConfigParser.SafeConfigParser(client_defaults)
720
 
    client_config.read(os.path.join(server_settings["configdir"],
721
 
                                    "clients.conf"))
722
 
    
723
 
    global service
724
 
    service = AvahiService(name = server_settings["servicename"],
725
 
                           type = "_mandos._tcp", );
726
 
    if server_settings["interface"]:
727
 
        service.interface = if_nametoindex(server_settings["interface"])
728
 
    
729
 
    global main_loop
730
 
    global bus
731
 
    global server
732
 
    # From the Avahi example code
733
 
    DBusGMainLoop(set_as_default=True )
734
 
    main_loop = gobject.MainLoop()
735
 
    bus = dbus.SystemBus()
736
 
    server = dbus.Interface(
737
 
            bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ),
738
 
            avahi.DBUS_INTERFACE_SERVER )
739
 
    # End of Avahi example code
740
 
    
741
 
    debug = server_settings["debug"]
742
 
    
743
 
    if debug:
744
 
        console = logging.StreamHandler()
745
 
        # console.setLevel(logging.DEBUG)
746
 
        console.setFormatter(logging.Formatter\
747
 
                             ('%(levelname)s: %(message)s'))
748
 
        logger.addHandler(console)
749
 
        del console
750
 
    
751
 
    clients = Set()
752
 
    def remove_from_clients(client):
753
 
        clients.remove(client)
754
 
        if not clients:
755
 
            logger.critical(u"No clients left, exiting")
756
 
            sys.exit()
757
 
    
758
 
    clients.update(Set(Client(name = section,
759
 
                              stop_hook = remove_from_clients,
760
 
                              config
761
 
                              = dict(client_config.items(section)))
762
 
                       for section in client_config.sections()))
763
 
    
764
 
    if not debug:
765
 
        daemon(False, False)
766
 
    
767
 
    def cleanup():
768
 
        "Cleanup function; run on exit"
769
 
        global group
770
 
        # From the Avahi example code
771
 
        if not group is None:
772
 
            group.Free()
773
 
            group = None
774
 
        # End of Avahi example code
775
 
        
776
 
        while clients:
777
 
            client = clients.pop()
778
 
            client.stop_hook = None
779
 
            client.stop()
780
 
    
781
 
    atexit.register(cleanup)
782
 
    
783
 
    if not debug:
784
 
        signal.signal(signal.SIGINT, signal.SIG_IGN)
785
 
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
786
 
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
787
 
    
788
 
    for client in clients:
789
 
        client.start()
790
 
    
791
 
    tcp_server = IPv6_TCPServer((server_settings["address"],
792
 
                                 server_settings["port"]),
793
 
                                tcp_handler,
794
 
                                settings=server_settings,
795
 
                                clients=clients)
796
 
    # Find out what port we got
797
 
    service.port = tcp_server.socket.getsockname()[1]
798
 
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
799
 
                u" scope_id %d" % tcp_server.socket.getsockname())
800
 
    
801
 
    #service.interface = tcp_server.socket.getsockname()[3]
802
 
    
803
 
    try:
804
 
        # From the Avahi example code
805
 
        server.connect_to_signal("StateChanged", server_state_changed)
806
 
        try:
807
 
            server_state_changed(server.GetState())
808
 
        except dbus.exceptions.DBusException, error:
809
 
            logger.critical(u"DBusException: %s", error)
810
 
            sys.exit(1)
811
 
        # End of Avahi example code
812
 
        
813
 
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
814
 
                             lambda *args, **kwargs:
815
 
                             tcp_server.handle_request\
816
 
                             (*args[2:], **kwargs) or True)
817
 
        
818
 
        logger.debug("Starting main loop")
819
 
        main_loop_started = True
820
 
        main_loop.run()
821
 
    except AvahiError, error:
822
 
        logger.critical(u"AvahiError: %s" + unicode(error))
823
 
        sys.exit(1)
824
 
    except KeyboardInterrupt:
825
 
        if debug:
826
 
            print
827
 
 
828
 
if __name__ == '__main__':
829
 
    main()