/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 mandos

  • Committer: Teddy Hogeborn
  • Date: 2008-09-17 00:34:09 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080917003409-bxbjsc4o69nx40t6
* .bzr-builddeb/default.conf: New.

* Makefile (install-server): Do not create directories that
                             should already be present in a
                             normal system.
  (install-client-nokey): - '' -  Also specify non-executable
                          mode for "initramfs-tools-hook-conf".

* README: Improved wording.  Use real copyright mark.

* debian/changelog: New.
* debian/compat: - '' -
* debian/control: - '' -
* debian/copyright: - '' -
* debian/mandos-client.README.Debian: - '' -
* debian/mandos-client.dirs: - '' -
* debian/mandos-client.lintian-overrides: - '' -
* debian/mandos-client.postinst: - '' -
* debian/mandos-client.postrm: - '' -
* debian/mandos.dirs: - '' -
* debian/mandos.lintian-overrides: - '' -
* debian/rules: - '' -
* default-mandos: - '' -

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 © 2008 Teddy Hogeborn
15
 
# Copyright © 2008 Björn Påhlsson
 
14
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
16
15
17
16
# This program is free software: you can redistribute it and/or modify
18
17
# it under the terms of the GNU General Public License as published by
31
30
# Contact the authors at <mandos@fukt.bsnet.se>.
32
31
33
32
 
34
 
from __future__ import division, with_statement, absolute_import
 
33
from __future__ import division
35
34
 
36
35
import SocketServer
37
36
import socket
 
37
import select
38
38
from optparse import OptionParser
39
39
import datetime
40
40
import errno
56
56
import logging
57
57
import logging.handlers
58
58
import pwd
59
 
from contextlib import closing
60
59
 
61
60
import dbus
62
 
import dbus.service
63
61
import gobject
64
62
import avahi
65
63
from dbus.mainloop.glib import DBusGMainLoop
66
64
import ctypes
67
 
import ctypes.util
68
65
 
69
 
version = "1.0.2"
 
66
version = "1.0"
70
67
 
71
68
logger = logging.Logger('mandos')
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'))
 
69
syslogger = logging.handlers.SysLogHandler\
 
70
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
71
             address = "/dev/log")
 
72
syslogger.setFormatter(logging.Formatter\
 
73
                        ('Mandos: %(levelname)s: %(message)s'))
77
74
logger.addHandler(syslogger)
78
75
 
79
76
console = logging.StreamHandler()
84
81
class AvahiError(Exception):
85
82
    def __init__(self, value):
86
83
        self.value = value
87
 
        super(AvahiError, self).__init__()
88
84
    def __str__(self):
89
85
        return repr(self.value)
90
86
 
112
108
                  a sensible number of times
113
109
    """
114
110
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
 
                 servicetype = None, port = None, TXT = None,
116
 
                 domain = "", host = "", max_renames = 32768):
 
111
                 type = None, port = None, TXT = None, domain = "",
 
112
                 host = "", max_renames = 32768):
117
113
        self.interface = interface
118
114
        self.name = name
119
 
        self.type = servicetype
 
115
        self.type = type
120
116
        self.port = port
121
 
        self.TXT = TXT if TXT is not None else []
 
117
        if TXT is None:
 
118
            self.TXT = []
 
119
        else:
 
120
            self.TXT = TXT
122
121
        self.domain = domain
123
122
        self.host = host
124
123
        self.rename_count = 0
128
127
        if self.rename_count >= self.max_renames:
129
128
            logger.critical(u"No suitable Zeroconf service name found"
130
129
                            u" after %i retries, exiting.",
131
 
                            self.rename_count)
 
130
                            rename_count)
132
131
            raise AvahiServiceError("Too many renames")
133
132
        self.name = server.GetAlternativeServiceName(self.name)
134
133
        logger.info(u"Changing Zeroconf service name to %r ...",
135
134
                    str(self.name))
136
 
        syslogger.setFormatter(logging.Formatter
 
135
        syslogger.setFormatter(logging.Formatter\
137
136
                               ('Mandos (%s): %%(levelname)s:'
138
 
                                ' %%(message)s' % self.name))
 
137
                               ' %%(message)s' % self.name))
139
138
        self.remove()
140
139
        self.add()
141
140
        self.rename_count += 1
147
146
        """Derived from the Avahi example code"""
148
147
        global group
149
148
        if group is None:
150
 
            group = dbus.Interface(bus.get_object
151
 
                                   (avahi.DBUS_NAME,
 
149
            group = dbus.Interface\
 
150
                    (bus.get_object(avahi.DBUS_NAME,
152
151
                                    server.EntryGroupNew()),
153
 
                                   avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
152
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
154
153
            group.connect_to_signal('StateChanged',
155
154
                                    entry_group_state_changed)
156
155
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
170
169
# End of Avahi example code
171
170
 
172
171
 
173
 
class Client(dbus.service.Object):
 
172
class Client(object):
174
173
    """A representation of a client host served by this server.
175
174
    Attributes:
176
175
    name:      string; from the config file, used in log messages
178
177
                 uniquely identify the client
179
178
    secret:    bytestring; sent verbatim (over TLS) to client
180
179
    host:      string; available for use by the checker command
181
 
    created:   datetime.datetime(); (UTC) object creation
182
 
    started:   datetime.datetime(); (UTC) last started
183
 
    last_checked_ok: datetime.datetime(); (UTC) or None
 
180
    created:   datetime.datetime(); object creation, not client host
 
181
    last_checked_ok: datetime.datetime() or None if not yet checked OK
184
182
    timeout:   datetime.timedelta(); How long from last_checked_ok
185
183
                                     until this client is invalid
186
184
    interval:  datetime.timedelta(); How often to start a new checker
202
200
    _interval_milliseconds: - '' -
203
201
    """
204
202
    def _set_timeout(self, timeout):
205
 
        "Setter function for the 'timeout' attribute"
 
203
        "Setter function for 'timeout' attribute"
206
204
        self._timeout = timeout
207
205
        self._timeout_milliseconds = ((self.timeout.days
208
206
                                       * 24 * 60 * 60 * 1000)
209
207
                                      + (self.timeout.seconds * 1000)
210
208
                                      + (self.timeout.microseconds
211
209
                                         // 1000))
212
 
        # Emit D-Bus signal
213
 
        self.TimeoutChanged(self._timeout_milliseconds)
214
 
    timeout = property(lambda self: self._timeout, _set_timeout)
 
210
    timeout = property(lambda self: self._timeout,
 
211
                       _set_timeout)
215
212
    del _set_timeout
216
 
    
217
213
    def _set_interval(self, interval):
218
 
        "Setter function for the 'interval' attribute"
 
214
        "Setter function for 'interval' attribute"
219
215
        self._interval = interval
220
216
        self._interval_milliseconds = ((self.interval.days
221
217
                                        * 24 * 60 * 60 * 1000)
223
219
                                          * 1000)
224
220
                                       + (self.interval.microseconds
225
221
                                          // 1000))
226
 
        # Emit D-Bus signal
227
 
        self.IntervalChanged(self._interval_milliseconds)
228
 
    interval = property(lambda self: self._interval, _set_interval)
 
222
    interval = property(lambda self: self._interval,
 
223
                        _set_interval)
229
224
    del _set_interval
230
 
    
231
 
    def __init__(self, name = None, stop_hook=None, config=None):
 
225
    def __init__(self, name = None, stop_hook=None, config={}):
232
226
        """Note: the 'checker' key in 'config' sets the
233
227
        'checker_command' attribute and *not* the 'checker'
234
228
        attribute."""
235
 
        dbus.service.Object.__init__(self, bus,
236
 
                                     "/Mandos/clients/%s"
237
 
                                     % name.replace(".", "_"))
238
 
        if config is None:
239
 
            config = {}
240
229
        self.name = name
241
230
        logger.debug(u"Creating client %r", self.name)
242
231
        # Uppercase and remove spaces from fingerprint for later
243
232
        # comparison purposes with return value from the fingerprint()
244
233
        # function
245
 
        self.fingerprint = (config["fingerprint"].upper()
246
 
                            .replace(u" ", u""))
 
234
        self.fingerprint = config["fingerprint"].upper()\
 
235
                           .replace(u" ", u"")
247
236
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
248
237
        if "secret" in config:
249
238
            self.secret = config["secret"].decode(u"base64")
250
239
        elif "secfile" in config:
251
 
            with closing(open(os.path.expanduser
252
 
                              (os.path.expandvars
253
 
                               (config["secfile"])))) as secfile:
254
 
                self.secret = secfile.read()
 
240
            sf = open(config["secfile"])
 
241
            self.secret = sf.read()
 
242
            sf.close()
255
243
        else:
256
244
            raise TypeError(u"No secret or secfile for client %s"
257
245
                            % self.name)
258
246
        self.host = config.get("host", "")
259
 
        self.created = datetime.datetime.utcnow()
260
 
        self.started = None
 
247
        self.created = datetime.datetime.now()
261
248
        self.last_checked_ok = None
262
249
        self.timeout = string_to_delta(config["timeout"])
263
250
        self.interval = string_to_delta(config["interval"])
267
254
        self.stop_initiator_tag = None
268
255
        self.checker_callback_tag = None
269
256
        self.check_command = config["checker"]
270
 
    
271
257
    def start(self):
272
258
        """Start this client's checker and timeout hooks"""
273
 
        self.started = datetime.datetime.utcnow()
274
259
        # Schedule a new checker to be started an 'interval' from now,
275
260
        # and every interval from then on.
276
 
        self.checker_initiator_tag = (gobject.timeout_add
277
 
                                      (self._interval_milliseconds,
278
 
                                       self.start_checker))
 
261
        self.checker_initiator_tag = gobject.timeout_add\
 
262
                                     (self._interval_milliseconds,
 
263
                                      self.start_checker)
279
264
        # Also start a new checker *right now*.
280
265
        self.start_checker()
281
266
        # Schedule a stop() when 'timeout' has passed
282
 
        self.stop_initiator_tag = (gobject.timeout_add
283
 
                                   (self._timeout_milliseconds,
284
 
                                    self.stop))
285
 
        # Emit D-Bus signal
286
 
        self.StateChanged(True)
287
 
    
 
267
        self.stop_initiator_tag = gobject.timeout_add\
 
268
                                  (self._timeout_milliseconds,
 
269
                                   self.stop)
288
270
    def stop(self):
289
 
        """Stop this client."""
290
 
        if getattr(self, "started", None) is not None:
 
271
        """Stop this client.
 
272
        The possibility that a client might be restarted is left open,
 
273
        but not currently used."""
 
274
        # If this client doesn't have a secret, it is already stopped.
 
275
        if hasattr(self, "secret") and self.secret:
291
276
            logger.info(u"Stopping client %s", self.name)
 
277
            self.secret = None
292
278
        else:
293
279
            return False
294
280
        if getattr(self, "stop_initiator_tag", False):
300
286
        self.stop_checker()
301
287
        if self.stop_hook:
302
288
            self.stop_hook(self)
303
 
        self.started = None
304
 
        # Emit D-Bus signal
305
 
        self.StateChanged(False)
306
289
        # Do not run this again if called by a gobject.timeout_add
307
290
        return False
308
 
    
309
291
    def __del__(self):
310
292
        self.stop_hook = None
311
293
        self.stop()
312
 
    
313
294
    def checker_callback(self, pid, condition):
314
295
        """The checker has completed, so take appropriate actions."""
 
296
        now = datetime.datetime.now()
315
297
        self.checker_callback_tag = None
316
298
        self.checker = None
317
 
        if (os.WIFEXITED(condition) 
318
 
            and (os.WEXITSTATUS(condition) == 0)):
 
299
        if os.WIFEXITED(condition) \
 
300
               and (os.WEXITSTATUS(condition) == 0):
319
301
            logger.info(u"Checker for %(name)s succeeded",
320
302
                        vars(self))
321
 
            # Emit D-Bus signal
322
 
            self.CheckerCompleted(True)
323
 
            self.bump_timeout()
 
303
            self.last_checked_ok = now
 
304
            gobject.source_remove(self.stop_initiator_tag)
 
305
            self.stop_initiator_tag = gobject.timeout_add\
 
306
                                      (self._timeout_milliseconds,
 
307
                                       self.stop)
324
308
        elif not os.WIFEXITED(condition):
325
309
            logger.warning(u"Checker for %(name)s crashed?",
326
310
                           vars(self))
327
 
            # Emit D-Bus signal
328
 
            self.CheckerCompleted(False)
329
311
        else:
330
312
            logger.info(u"Checker for %(name)s failed",
331
313
                        vars(self))
332
 
            # Emit D-Bus signal
333
 
            self.CheckerCompleted(False)
334
 
    
335
 
    def bump_timeout(self):
336
 
        """Bump up the timeout for this client.
337
 
        This should only be called when the client has been seen,
338
 
        alive and well.
339
 
        """
340
 
        self.last_checked_ok = datetime.datetime.utcnow()
341
 
        gobject.source_remove(self.stop_initiator_tag)
342
 
        self.stop_initiator_tag = (gobject.timeout_add
343
 
                                   (self._timeout_milliseconds,
344
 
                                    self.stop))
345
 
    
346
314
    def start_checker(self):
347
315
        """Start a new checker subprocess if one is not running.
348
316
        If a checker already exists, leave it running and do
380
348
                self.checker = subprocess.Popen(command,
381
349
                                                close_fds=True,
382
350
                                                shell=True, cwd="/")
383
 
                self.checker_callback_tag = (gobject.child_watch_add
384
 
                                             (self.checker.pid,
385
 
                                              self.checker_callback))
386
 
                # Emit D-Bus signal
387
 
                self.CheckerStarted(command)
 
351
                self.checker_callback_tag = gobject.child_watch_add\
 
352
                                            (self.checker.pid,
 
353
                                             self.checker_callback)
388
354
            except OSError, error:
389
355
                logger.error(u"Failed to start subprocess: %s",
390
356
                             error)
391
357
        # Re-run this periodically if run by gobject.timeout_add
392
358
        return True
393
 
    
394
359
    def stop_checker(self):
395
360
        """Force the checker process, if any, to stop."""
396
361
        if self.checker_callback_tag:
408
373
            if error.errno != errno.ESRCH: # No such process
409
374
                raise
410
375
        self.checker = None
411
 
    
412
376
    def still_valid(self):
413
377
        """Has the timeout not yet passed for this client?"""
414
 
        if not self.started:
415
 
            return False
416
 
        now = datetime.datetime.utcnow()
 
378
        now = datetime.datetime.now()
417
379
        if self.last_checked_ok is None:
418
380
            return now < (self.created + self.timeout)
419
381
        else:
420
382
            return now < (self.last_checked_ok + self.timeout)
421
 
    
422
 
    ## D-Bus methods & signals
423
 
    _interface = u"org.mandos_system.Mandos.Client"
424
 
    
425
 
    def _datetime_to_dbus_struct(dt):
426
 
        return dbus.Struct(dt.year, dt.month, dt.day, dt.hour,
427
 
                           dt.minute, dt.second, dt.microsecond,
428
 
                           signature="nyyyyyu")
429
 
    
430
 
    # BumpTimeout - method
431
 
    BumpTimeout = dbus.service.method(_interface)(bump_timeout)
432
 
    BumpTimeout.__name__ = "BumpTimeout"
433
 
    
434
 
    # IntervalChanged - signal
435
 
    @dbus.service.signal(_interface, signature="t")
436
 
    def IntervalChanged(self, t):
437
 
        "D-Bus signal"
438
 
        pass
439
 
    
440
 
    # CheckerCompleted - signal
441
 
    @dbus.service.signal(_interface, signature="b")
442
 
    def CheckerCompleted(self, success):
443
 
        "D-Bus signal"
444
 
        pass
445
 
    
446
 
    # CheckerIsRunning - method
447
 
    @dbus.service.method(_interface, out_signature="b")
448
 
    def CheckerIsRunning(self):
449
 
        "D-Bus getter method"
450
 
        return self.checker is not None
451
 
    
452
 
    # CheckerStarted - signal
453
 
    @dbus.service.signal(_interface, signature="s")
454
 
    def CheckerStarted(self, command):
455
 
        "D-Bus signal"
456
 
        pass
457
 
    
458
 
    # GetChecker - method
459
 
    @dbus.service.method(_interface, out_signature="s")
460
 
    def GetChecker(self):
461
 
        "D-Bus getter method"
462
 
        return self.checker_command
463
 
    
464
 
    # GetCreated - method
465
 
    @dbus.service.method(_interface, out_signature="(nyyyyyu)")
466
 
    def GetCreated(self):
467
 
        "D-Bus getter method"
468
 
        return datetime_to_dbus_struct(self.created)
469
 
    
470
 
    # GetFingerprint - method
471
 
    @dbus.service.method(_interface, out_signature="s")
472
 
    def GetFingerprint(self):
473
 
        "D-Bus getter method"
474
 
        return self.fingerprint
475
 
    
476
 
    # GetHost - method
477
 
    @dbus.service.method(_interface, out_signature="s")
478
 
    def GetHost(self):
479
 
        "D-Bus getter method"
480
 
        return self.host
481
 
    
482
 
    # GetInterval - method
483
 
    @dbus.service.method(_interface, out_signature="t")
484
 
    def GetInterval(self):
485
 
        "D-Bus getter method"
486
 
        return self._interval_milliseconds
487
 
    
488
 
    # GetName - method
489
 
    @dbus.service.method(_interface, out_signature="s")
490
 
    def GetName(self):
491
 
        "D-Bus getter method"
492
 
        return self.name
493
 
    
494
 
    # GetStarted - method
495
 
    @dbus.service.method(_interface, out_signature="(nyyyyyu)")
496
 
    def GetStarted(self):
497
 
        "D-Bus getter method"
498
 
        if self.started is not None:
499
 
            return datetime_to_dbus_struct(self.started)
500
 
        else:
501
 
            return dbus.Struct(0, 0, 0, 0, 0, 0, 0,
502
 
                               signature="nyyyyyu")
503
 
    
504
 
    # GetTimeout - method
505
 
    @dbus.service.method(_interface, out_signature="t")
506
 
    def GetTimeout(self):
507
 
        "D-Bus getter method"
508
 
        return self._timeout_milliseconds
509
 
    
510
 
    # SetChecker - method
511
 
    @dbus.service.method(_interface, in_signature="s")
512
 
    def SetChecker(self, checker):
513
 
        "D-Bus setter method"
514
 
        self.checker_command = checker
515
 
    
516
 
    # SetHost - method
517
 
    @dbus.service.method(_interface, in_signature="s")
518
 
    def SetHost(self, host):
519
 
        "D-Bus setter method"
520
 
        self.host = host
521
 
    
522
 
    # SetInterval - method
523
 
    @dbus.service.method(_interface, in_signature="t")
524
 
    def SetInterval(self, milliseconds):
525
 
        self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
526
 
    
527
 
    # SetTimeout - method
528
 
    @dbus.service.method(_interface, in_signature="t")
529
 
    def SetTimeout(self, milliseconds):
530
 
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
531
 
    
532
 
    # SetSecret - method
533
 
    @dbus.service.method(_interface, in_signature="ay",
534
 
                         byte_arrays=True)
535
 
    def SetSecret(self, secret):
536
 
        "D-Bus setter method"
537
 
        self.secret = str(secret)
538
 
    
539
 
    # Start - method
540
 
    Start = dbus.service.method(_interface)(start)
541
 
    Start.__name__ = "Start"
542
 
    
543
 
    # StartChecker - method
544
 
    StartChecker = dbus.service.method(_interface)(start_checker)
545
 
    StartChecker.__name__ = "StartChecker"
546
 
    
547
 
    # StateChanged - signal
548
 
    @dbus.service.signal(_interface, signature="b")
549
 
    def StateChanged(self, started):
550
 
        "D-Bus signal"
551
 
        pass
552
 
    
553
 
    # StillValid - method
554
 
    StillValid = (dbus.service.method(_interface, out_signature="b")
555
 
                  (still_valid))
556
 
    StillValid.__name__ = "StillValid"
557
 
    
558
 
    # Stop - method
559
 
    Stop = dbus.service.method(_interface)(stop)
560
 
    Stop.__name__ = "Stop"
561
 
    
562
 
    # StopChecker - method
563
 
    StopChecker = dbus.service.method(_interface)(stop_checker)
564
 
    StopChecker.__name__ = "StopChecker"
565
 
    
566
 
    # TimeoutChanged - signal
567
 
    @dbus.service.signal(_interface, signature="t")
568
 
    def TimeoutChanged(self, t):
569
 
        "D-Bus signal"
570
 
        pass
571
 
    
572
 
    del _datetime_to_dbus_struct
573
 
    del _interface
574
383
 
575
384
 
576
385
def peer_certificate(session):
577
386
    "Return the peer's OpenPGP certificate as a bytestring"
578
387
    # If not an OpenPGP certificate...
579
 
    if (gnutls.library.functions
580
 
        .gnutls_certificate_type_get(session._c_object)
581
 
        != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
388
    if gnutls.library.functions.gnutls_certificate_type_get\
 
389
            (session._c_object) \
 
390
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
582
391
        # ...do the normal thing
583
392
        return session.peer_certificate
584
393
    list_size = ctypes.c_uint()
585
 
    cert_list = (gnutls.library.functions
586
 
                 .gnutls_certificate_get_peers
587
 
                 (session._c_object, ctypes.byref(list_size)))
 
394
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
 
395
        (session._c_object, ctypes.byref(list_size))
588
396
    if list_size.value == 0:
589
397
        return None
590
398
    cert = cert_list[0]
594
402
def fingerprint(openpgp):
595
403
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
596
404
    # New GnuTLS "datum" with the OpenPGP public key
597
 
    datum = (gnutls.library.types
598
 
             .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
599
 
                                         ctypes.POINTER
600
 
                                         (ctypes.c_ubyte)),
601
 
                             ctypes.c_uint(len(openpgp))))
 
405
    datum = gnutls.library.types.gnutls_datum_t\
 
406
        (ctypes.cast(ctypes.c_char_p(openpgp),
 
407
                     ctypes.POINTER(ctypes.c_ubyte)),
 
408
         ctypes.c_uint(len(openpgp)))
602
409
    # New empty GnuTLS certificate
603
410
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
604
 
    (gnutls.library.functions
605
 
     .gnutls_openpgp_crt_init(ctypes.byref(crt)))
 
411
    gnutls.library.functions.gnutls_openpgp_crt_init\
 
412
        (ctypes.byref(crt))
606
413
    # Import the OpenPGP public key into the certificate
607
 
    (gnutls.library.functions
608
 
     .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
609
 
                                gnutls.library.constants
610
 
                                .GNUTLS_OPENPGP_FMT_RAW))
 
414
    gnutls.library.functions.gnutls_openpgp_crt_import\
 
415
                    (crt, ctypes.byref(datum),
 
416
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
611
417
    # Verify the self signature in the key
612
 
    crtverify = ctypes.c_uint()
613
 
    (gnutls.library.functions
614
 
     .gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
 
418
    crtverify = ctypes.c_uint();
 
419
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
 
420
        (crt, 0, ctypes.byref(crtverify))
615
421
    if crtverify.value != 0:
616
422
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
617
423
        raise gnutls.errors.CertificateSecurityError("Verify failed")
618
424
    # New buffer for the fingerprint
619
 
    buf = ctypes.create_string_buffer(20)
620
 
    buf_len = ctypes.c_size_t()
 
425
    buffer = ctypes.create_string_buffer(20)
 
426
    buffer_length = ctypes.c_size_t()
621
427
    # Get the fingerprint from the certificate into the buffer
622
 
    (gnutls.library.functions
623
 
     .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
624
 
                                         ctypes.byref(buf_len)))
 
428
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
 
429
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
625
430
    # Deinit the certificate
626
431
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
627
432
    # Convert the buffer to a Python bytestring
628
 
    fpr = ctypes.string_at(buf, buf_len.value)
 
433
    fpr = ctypes.string_at(buffer, buffer_length.value)
629
434
    # Convert the bytestring to hexadecimal notation
630
435
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
631
436
    return hex_fpr
632
437
 
633
438
 
634
 
class TCP_handler(SocketServer.BaseRequestHandler, object):
 
439
class tcp_handler(SocketServer.BaseRequestHandler, object):
635
440
    """A TCP request handler class.
636
441
    Instantiated by IPv6_TCPServer for each request to handle it.
637
442
    Note: This will run in its own forked process."""
638
443
    
639
444
    def handle(self):
640
445
        logger.info(u"TCP connection from: %s",
641
 
                    unicode(self.client_address))
642
 
        session = (gnutls.connection
643
 
                   .ClientSession(self.request,
644
 
                                  gnutls.connection
645
 
                                  .X509Credentials()))
 
446
                     unicode(self.client_address))
 
447
        session = gnutls.connection.ClientSession\
 
448
                  (self.request, gnutls.connection.X509Credentials())
646
449
        
647
450
        line = self.request.makefile().readline()
648
451
        logger.debug(u"Protocol version: %r", line)
661
464
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
662
465
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
663
466
        #                "+DHE-DSS"))
664
 
        # Use a fallback default, since this MUST be set.
665
 
        priority = self.server.settings.get("priority", "NORMAL")
666
 
        (gnutls.library.functions
667
 
         .gnutls_priority_set_direct(session._c_object,
668
 
                                     priority, None))
 
467
        priority = "NORMAL"             # Fallback default, since this
 
468
                                        # MUST be set.
 
469
        if self.server.settings["priority"]:
 
470
            priority = self.server.settings["priority"]
 
471
        gnutls.library.functions.gnutls_priority_set_direct\
 
472
            (session._c_object, priority, None);
669
473
        
670
474
        try:
671
475
            session.handshake()
681
485
            session.bye()
682
486
            return
683
487
        logger.debug(u"Fingerprint: %s", fpr)
 
488
        client = None
684
489
        for c in self.server.clients:
685
490
            if c.fingerprint == fpr:
686
491
                client = c
687
492
                break
688
 
        else:
 
493
        if not client:
689
494
            logger.warning(u"Client not found for fingerprint: %s",
690
495
                           fpr)
691
496
            session.bye()
698
503
                           vars(client))
699
504
            session.bye()
700
505
            return
701
 
        ## This won't work here, since we're in a fork.
702
 
        # client.bump_timeout()
703
506
        sent_size = 0
704
507
        while sent_size < len(client.secret):
705
508
            sent = session.send(client.secret[sent_size:])
710
513
        session.bye()
711
514
 
712
515
 
713
 
class IPv6_TCPServer(SocketServer.ForkingMixIn,
714
 
                     SocketServer.TCPServer, object):
 
516
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
715
517
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
716
518
    Attributes:
717
519
        settings:       Server settings
727
529
            self.clients = kwargs["clients"]
728
530
            del kwargs["clients"]
729
531
        self.enabled = False
730
 
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
 
532
        return super(type(self), self).__init__(*args, **kwargs)
731
533
    def server_bind(self):
732
534
        """This overrides the normal server_bind() function
733
535
        to bind to an interface if one was specified, and also NOT to
762
564
#                                            if_nametoindex
763
565
#                                            (self.settings
764
566
#                                             ["interface"]))
765
 
            return super(IPv6_TCPServer, self).server_bind()
 
567
            return super(type(self), self).server_bind()
766
568
    def server_activate(self):
767
569
        if self.enabled:
768
 
            return super(IPv6_TCPServer, self).server_activate()
 
570
            return super(type(self), self).server_activate()
769
571
    def enable(self):
770
572
        self.enabled = True
771
573
 
789
591
    timevalue = datetime.timedelta(0)
790
592
    for s in interval.split():
791
593
        try:
792
 
            suffix = unicode(s[-1])
793
 
            value = int(s[:-1])
 
594
            suffix=unicode(s[-1])
 
595
            value=int(s[:-1])
794
596
            if suffix == u"d":
795
597
                delta = datetime.timedelta(value)
796
598
            elif suffix == u"s":
836
638
    """Call the C function if_nametoindex(), or equivalent"""
837
639
    global if_nametoindex
838
640
    try:
839
 
        if_nametoindex = (ctypes.cdll.LoadLibrary
840
 
                          (ctypes.util.find_library("c"))
841
 
                          .if_nametoindex)
 
641
        if "ctypes.util" not in sys.modules:
 
642
            import ctypes.util
 
643
        if_nametoindex = ctypes.cdll.LoadLibrary\
 
644
            (ctypes.util.find_library("c")).if_nametoindex
842
645
    except (OSError, AttributeError):
843
646
        if "struct" not in sys.modules:
844
647
            import struct
847
650
        def if_nametoindex(interface):
848
651
            "Get an interface index the hard way, i.e. using fcntl()"
849
652
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
850
 
            with closing(socket.socket()) as s:
851
 
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
852
 
                                    struct.pack("16s16x", interface))
 
653
            s = socket.socket()
 
654
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
655
                                struct.pack("16s16x", interface))
 
656
            s.close()
853
657
            interface_index = struct.unpack("I", ifreq[16:20])[0]
854
658
            return interface_index
855
659
    return if_nametoindex(interface)
879
683
 
880
684
 
881
685
def main():
 
686
    global main_loop_started
 
687
    main_loop_started = False
 
688
    
882
689
    parser = OptionParser(version = "%%prog %s" % version)
883
690
    parser.add_option("-i", "--interface", type="string",
884
691
                      metavar="IF", help="Bind to interface IF")
899
706
                      default="/etc/mandos", metavar="DIR",
900
707
                      help="Directory to search for configuration"
901
708
                      " files")
902
 
    options = parser.parse_args()[0]
 
709
    (options, args) = parser.parse_args()
903
710
    
904
711
    if options.check:
905
712
        import doctest
923
730
    # Convert the SafeConfigParser object to a dict
924
731
    server_settings = server_config.defaults()
925
732
    # Use getboolean on the boolean config option
926
 
    server_settings["debug"] = (server_config.getboolean
927
 
                                ("DEFAULT", "debug"))
 
733
    server_settings["debug"] = server_config.getboolean\
 
734
                               ("DEFAULT", "debug")
928
735
    del server_config
929
736
    
930
737
    # Override the settings from the config file with command line
944
751
        console.setLevel(logging.WARNING)
945
752
    
946
753
    if server_settings["servicename"] != "Mandos":
947
 
        syslogger.setFormatter(logging.Formatter
 
754
        syslogger.setFormatter(logging.Formatter\
948
755
                               ('Mandos (%s): %%(levelname)s:'
949
756
                                ' %%(message)s'
950
757
                                % server_settings["servicename"]))
962
769
    clients = Set()
963
770
    tcp_server = IPv6_TCPServer((server_settings["address"],
964
771
                                 server_settings["port"]),
965
 
                                TCP_handler,
 
772
                                tcp_handler,
966
773
                                settings=server_settings,
967
774
                                clients=clients)
968
775
    pidfilename = "/var/run/mandos.pid"
996
803
    
997
804
    global service
998
805
    service = AvahiService(name = server_settings["servicename"],
999
 
                           servicetype = "_mandos._tcp", )
 
806
                           type = "_mandos._tcp", );
1000
807
    if server_settings["interface"]:
1001
 
        service.interface = (if_nametoindex
1002
 
                             (server_settings["interface"]))
 
808
        service.interface = if_nametoindex\
 
809
                            (server_settings["interface"])
1003
810
    
1004
811
    global main_loop
1005
812
    global bus
1012
819
                                           avahi.DBUS_PATH_SERVER),
1013
820
                            avahi.DBUS_INTERFACE_SERVER)
1014
821
    # End of Avahi example code
1015
 
    bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
1016
822
    
1017
823
    def remove_from_clients(client):
1018
824
        clients.remove(client)
1046
852
        pidfile.write(str(pid) + "\n")
1047
853
        pidfile.close()
1048
854
        del pidfile
1049
 
    except IOError:
 
855
    except IOError, err:
1050
856
        logger.error(u"Could not write to file %r with PID %d",
1051
857
                     pidfilename, pid)
1052
858
    except NameError:
1100
906
        
1101
907
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
1102
908
                             lambda *args, **kwargs:
1103
 
                             (tcp_server.handle_request
1104
 
                              (*args[2:], **kwargs) or True))
 
909
                             tcp_server.handle_request\
 
910
                             (*args[2:], **kwargs) or True)
1105
911
        
1106
912
        logger.debug(u"Starting main loop")
 
913
        main_loop_started = True
1107
914
        main_loop.run()
1108
915
    except AvahiError, error:
1109
916
        logger.critical(u"AvahiError: %s" + unicode(error))