/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-13 15:36:18 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080913153618-atp386q2bqj0ku99
* Makefile (install-client-nokey): Do "&&" instead of ";" to catch
                                   errors.

* README: Kill the straight quotes.  Add copyright notice.

* overview.xml: Improved wording.

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
 
def _datetime_to_dbus_struct(dt, variant_level=0):
174
 
    """Convert a UTC datetime.datetime() to a D-Bus struct.
175
 
    The format is special to this application, since we could not find
176
 
    any other standard way."""
177
 
    return dbus.Struct((dbus.Int16(dt.year),
178
 
                        dbus.Byte(dt.month),
179
 
                        dbus.Byte(dt.day),
180
 
                        dbus.Byte(dt.hour),
181
 
                        dbus.Byte(dt.minute),
182
 
                        dbus.Byte(dt.second),
183
 
                        dbus.UInt32(dt.microsecond)),
184
 
                       signature="nyyyyyu",
185
 
                       variant_level=variant_level)
186
 
 
187
 
 
188
 
class Client(dbus.service.Object):
 
172
class Client(object):
189
173
    """A representation of a client host served by this server.
190
174
    Attributes:
191
 
    name:       string; from the config file, used in log messages
 
175
    name:      string; from the config file, used in log messages
192
176
    fingerprint: string (40 or 32 hexadecimal digits); used to
193
177
                 uniquely identify the client
194
 
    secret:     bytestring; sent verbatim (over TLS) to client
195
 
    host:       string; available for use by the checker command
196
 
    created:    datetime.datetime(); (UTC) object creation
197
 
    last_started: datetime.datetime(); (UTC)
198
 
    started:    bool()
199
 
    last_checked_ok: datetime.datetime(); (UTC) or None
200
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
201
 
                                      until this client is invalid
202
 
    interval:   datetime.timedelta(); How often to start a new checker
203
 
    stop_hook:  If set, called by stop() as stop_hook(self)
204
 
    checker:    subprocess.Popen(); a running checker process used
205
 
                                    to see if the client lives.
206
 
                                    'None' if no process is running.
 
178
    secret:    bytestring; sent verbatim (over TLS) to client
 
179
    host:      string; available for use by the checker command
 
180
    created:   datetime.datetime(); object creation, not client host
 
181
    last_checked_ok: datetime.datetime() or None if not yet checked OK
 
182
    timeout:   datetime.timedelta(); How long from last_checked_ok
 
183
                                     until this client is invalid
 
184
    interval:  datetime.timedelta(); How often to start a new checker
 
185
    stop_hook: If set, called by stop() as stop_hook(self)
 
186
    checker:   subprocess.Popen(); a running checker process used
 
187
                                   to see if the client lives.
 
188
                                   'None' if no process is running.
207
189
    checker_initiator_tag: a gobject event source tag, or None
208
190
    stop_initiator_tag:    - '' -
209
191
    checker_callback_tag:  - '' -
211
193
                     client lives.  %() expansions are done at
212
194
                     runtime with vars(self) as dict, so that for
213
195
                     instance %(name)s can be used in the command.
214
 
    dbus_object_path: dbus.ObjectPath
215
196
    Private attibutes:
216
197
    _timeout: Real variable for 'timeout'
217
198
    _interval: Real variable for 'interval'
219
200
    _interval_milliseconds: - '' -
220
201
    """
221
202
    def _set_timeout(self, timeout):
222
 
        "Setter function for the 'timeout' attribute"
 
203
        "Setter function for 'timeout' attribute"
223
204
        self._timeout = timeout
224
205
        self._timeout_milliseconds = ((self.timeout.days
225
206
                                       * 24 * 60 * 60 * 1000)
226
207
                                      + (self.timeout.seconds * 1000)
227
208
                                      + (self.timeout.microseconds
228
209
                                         // 1000))
229
 
        # Emit D-Bus signal
230
 
        self.PropertyChanged(dbus.String(u"timeout"),
231
 
                             (dbus.UInt64(self._timeout_milliseconds,
232
 
                                          variant_level=1)))
233
 
    timeout = property(lambda self: self._timeout, _set_timeout)
 
210
    timeout = property(lambda self: self._timeout,
 
211
                       _set_timeout)
234
212
    del _set_timeout
235
 
    
236
213
    def _set_interval(self, interval):
237
 
        "Setter function for the 'interval' attribute"
 
214
        "Setter function for 'interval' attribute"
238
215
        self._interval = interval
239
216
        self._interval_milliseconds = ((self.interval.days
240
217
                                        * 24 * 60 * 60 * 1000)
242
219
                                          * 1000)
243
220
                                       + (self.interval.microseconds
244
221
                                          // 1000))
245
 
        # Emit D-Bus signal
246
 
        self.PropertyChanged(dbus.String(u"interval"),
247
 
                             (dbus.UInt64(self._interval_milliseconds,
248
 
                                          variant_level=1)))
249
 
    interval = property(lambda self: self._interval, _set_interval)
 
222
    interval = property(lambda self: self._interval,
 
223
                        _set_interval)
250
224
    del _set_interval
251
 
    
252
 
    def __init__(self, name = None, stop_hook=None, config=None):
 
225
    def __init__(self, name = None, stop_hook=None, config={}):
253
226
        """Note: the 'checker' key in 'config' sets the
254
227
        'checker_command' attribute and *not* the 'checker'
255
228
        attribute."""
256
 
        self.dbus_object_path = (dbus.ObjectPath
257
 
                                 ("/Mandos/clients/"
258
 
                                  + name.replace(".", "_")))
259
 
        dbus.service.Object.__init__(self, bus,
260
 
                                     self.dbus_object_path)
261
 
        if config is None:
262
 
            config = {}
263
229
        self.name = name
264
230
        logger.debug(u"Creating client %r", self.name)
265
231
        # Uppercase and remove spaces from fingerprint for later
266
232
        # comparison purposes with return value from the fingerprint()
267
233
        # function
268
 
        self.fingerprint = (config["fingerprint"].upper()
269
 
                            .replace(u" ", u""))
 
234
        self.fingerprint = config["fingerprint"].upper()\
 
235
                           .replace(u" ", u"")
270
236
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
271
237
        if "secret" in config:
272
238
            self.secret = config["secret"].decode(u"base64")
273
239
        elif "secfile" in config:
274
 
            with closing(open(os.path.expanduser
275
 
                              (os.path.expandvars
276
 
                               (config["secfile"])))) as secfile:
277
 
                self.secret = secfile.read()
 
240
            sf = open(config["secfile"])
 
241
            self.secret = sf.read()
 
242
            sf.close()
278
243
        else:
279
244
            raise TypeError(u"No secret or secfile for client %s"
280
245
                            % self.name)
281
246
        self.host = config.get("host", "")
282
 
        self.created = datetime.datetime.utcnow()
283
 
        self.started = False
284
 
        self.last_started = None
 
247
        self.created = datetime.datetime.now()
285
248
        self.last_checked_ok = None
286
249
        self.timeout = string_to_delta(config["timeout"])
287
250
        self.interval = string_to_delta(config["interval"])
290
253
        self.checker_initiator_tag = None
291
254
        self.stop_initiator_tag = None
292
255
        self.checker_callback_tag = None
293
 
        self.checker_command = config["checker"]
294
 
    
 
256
        self.check_command = config["checker"]
295
257
    def start(self):
296
258
        """Start this client's checker and timeout hooks"""
297
 
        self.last_started = datetime.datetime.utcnow()
298
259
        # Schedule a new checker to be started an 'interval' from now,
299
260
        # and every interval from then on.
300
 
        self.checker_initiator_tag = (gobject.timeout_add
301
 
                                      (self._interval_milliseconds,
302
 
                                       self.start_checker))
 
261
        self.checker_initiator_tag = gobject.timeout_add\
 
262
                                     (self._interval_milliseconds,
 
263
                                      self.start_checker)
303
264
        # Also start a new checker *right now*.
304
265
        self.start_checker()
305
266
        # Schedule a stop() when 'timeout' has passed
306
 
        self.stop_initiator_tag = (gobject.timeout_add
307
 
                                   (self._timeout_milliseconds,
308
 
                                    self.stop))
309
 
        self.started = True
310
 
        # Emit D-Bus signal
311
 
        self.PropertyChanged(dbus.String(u"started"),
312
 
                             dbus.Boolean(True, variant_level=1))
313
 
        self.PropertyChanged(dbus.String(u"last_started"),
314
 
                             (_datetime_to_dbus_struct
315
 
                              (self.last_started, variant_level=1)))
316
 
    
 
267
        self.stop_initiator_tag = gobject.timeout_add\
 
268
                                  (self._timeout_milliseconds,
 
269
                                   self.stop)
317
270
    def stop(self):
318
 
        """Stop this client."""
319
 
        if not getattr(self, "started", False):
 
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:
 
276
            logger.info(u"Stopping client %s", self.name)
 
277
            self.secret = None
 
278
        else:
320
279
            return False
321
 
        logger.info(u"Stopping client %s", self.name)
322
280
        if getattr(self, "stop_initiator_tag", False):
323
281
            gobject.source_remove(self.stop_initiator_tag)
324
282
            self.stop_initiator_tag = None
328
286
        self.stop_checker()
329
287
        if self.stop_hook:
330
288
            self.stop_hook(self)
331
 
        self.started = False
332
 
        # Emit D-Bus signal
333
 
        self.PropertyChanged(dbus.String(u"started"),
334
 
                             dbus.Boolean(False, variant_level=1))
335
289
        # Do not run this again if called by a gobject.timeout_add
336
290
        return False
337
 
    
338
291
    def __del__(self):
339
292
        self.stop_hook = None
340
293
        self.stop()
341
 
    
342
 
    def checker_callback(self, pid, condition, command):
 
294
    def checker_callback(self, pid, condition):
343
295
        """The checker has completed, so take appropriate actions."""
 
296
        now = datetime.datetime.now()
344
297
        self.checker_callback_tag = None
345
298
        self.checker = None
346
 
        # Emit D-Bus signal
347
 
        self.PropertyChanged(dbus.String(u"checker_running"),
348
 
                             dbus.Boolean(False, variant_level=1))
349
 
        if (os.WIFEXITED(condition)
350
 
            and (os.WEXITSTATUS(condition) == 0)):
 
299
        if os.WIFEXITED(condition) \
 
300
               and (os.WEXITSTATUS(condition) == 0):
351
301
            logger.info(u"Checker for %(name)s succeeded",
352
302
                        vars(self))
353
 
            # Emit D-Bus signal
354
 
            self.CheckerCompleted(dbus.Boolean(True),
355
 
                                  dbus.UInt16(condition),
356
 
                                  dbus.String(command))
357
 
            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)
358
308
        elif not os.WIFEXITED(condition):
359
309
            logger.warning(u"Checker for %(name)s crashed?",
360
310
                           vars(self))
361
 
            # Emit D-Bus signal
362
 
            self.CheckerCompleted(dbus.Boolean(False),
363
 
                                  dbus.UInt16(condition),
364
 
                                  dbus.String(command))
365
311
        else:
366
312
            logger.info(u"Checker for %(name)s failed",
367
313
                        vars(self))
368
 
            # Emit D-Bus signal
369
 
            self.CheckerCompleted(dbus.Boolean(False),
370
 
                                  dbus.UInt16(condition),
371
 
                                  dbus.String(command))
372
 
    
373
 
    def bump_timeout(self):
374
 
        """Bump up the timeout for this client.
375
 
        This should only be called when the client has been seen,
376
 
        alive and well.
377
 
        """
378
 
        self.last_checked_ok = datetime.datetime.utcnow()
379
 
        gobject.source_remove(self.stop_initiator_tag)
380
 
        self.stop_initiator_tag = (gobject.timeout_add
381
 
                                   (self._timeout_milliseconds,
382
 
                                    self.stop))
383
 
        self.PropertyChanged(dbus.String(u"last_checked_ok"),
384
 
                             (_datetime_to_dbus_struct
385
 
                              (self.last_checked_ok,
386
 
                               variant_level=1)))
387
 
    
388
314
    def start_checker(self):
389
315
        """Start a new checker subprocess if one is not running.
390
316
        If a checker already exists, leave it running and do
399
325
        # is as it should be.
400
326
        if self.checker is None:
401
327
            try:
402
 
                # In case checker_command has exactly one % operator
403
 
                command = self.checker_command % self.host
 
328
                # In case check_command has exactly one % operator
 
329
                command = self.check_command % self.host
404
330
            except TypeError:
405
331
                # Escape attributes for the shell
406
332
                escaped_attrs = dict((key, re.escape(str(val)))
407
333
                                     for key, val in
408
334
                                     vars(self).iteritems())
409
335
                try:
410
 
                    command = self.checker_command % escaped_attrs
 
336
                    command = self.check_command % escaped_attrs
411
337
                except TypeError, error:
412
338
                    logger.error(u'Could not format string "%s":'
413
 
                                 u' %s', self.checker_command, error)
 
339
                                 u' %s', self.check_command, error)
414
340
                    return True # Try again later
415
341
            try:
416
342
                logger.info(u"Starting checker %r for %s",
422
348
                self.checker = subprocess.Popen(command,
423
349
                                                close_fds=True,
424
350
                                                shell=True, cwd="/")
425
 
                # Emit D-Bus signal
426
 
                self.CheckerStarted(command)
427
 
                self.PropertyChanged(dbus.String("checker_running"),
428
 
                                     dbus.Boolean(True, variant_level=1))
429
 
                self.checker_callback_tag = (gobject.child_watch_add
430
 
                                             (self.checker.pid,
431
 
                                              self.checker_callback,
432
 
                                              data=command))
 
351
                self.checker_callback_tag = gobject.child_watch_add\
 
352
                                            (self.checker.pid,
 
353
                                             self.checker_callback)
433
354
            except OSError, error:
434
355
                logger.error(u"Failed to start subprocess: %s",
435
356
                             error)
436
357
        # Re-run this periodically if run by gobject.timeout_add
437
358
        return True
438
 
    
439
359
    def stop_checker(self):
440
360
        """Force the checker process, if any, to stop."""
441
361
        if self.checker_callback_tag:
453
373
            if error.errno != errno.ESRCH: # No such process
454
374
                raise
455
375
        self.checker = None
456
 
        self.PropertyChanged(dbus.String(u"checker_running"),
457
 
                             dbus.Boolean(False, variant_level=1))
458
 
    
459
376
    def still_valid(self):
460
377
        """Has the timeout not yet passed for this client?"""
461
 
        if not getattr(self, "started", False):
462
 
            return False
463
 
        now = datetime.datetime.utcnow()
 
378
        now = datetime.datetime.now()
464
379
        if self.last_checked_ok is None:
465
380
            return now < (self.created + self.timeout)
466
381
        else:
467
382
            return now < (self.last_checked_ok + self.timeout)
468
 
    
469
 
    ## D-Bus methods & signals
470
 
    _interface = u"org.mandos_system.Mandos.Client"
471
 
    
472
 
    # BumpTimeout - method
473
 
    BumpTimeout = dbus.service.method(_interface)(bump_timeout)
474
 
    BumpTimeout.__name__ = "BumpTimeout"
475
 
    
476
 
    # CheckerCompleted - signal
477
 
    @dbus.service.signal(_interface, signature="bqs")
478
 
    def CheckerCompleted(self, success, condition, command):
479
 
        "D-Bus signal"
480
 
        pass
481
 
    
482
 
    # CheckerStarted - signal
483
 
    @dbus.service.signal(_interface, signature="s")
484
 
    def CheckerStarted(self, command):
485
 
        "D-Bus signal"
486
 
        pass
487
 
    
488
 
    # GetAllProperties - method
489
 
    @dbus.service.method(_interface, out_signature="a{sv}")
490
 
    def GetAllProperties(self):
491
 
        "D-Bus method"
492
 
        return dbus.Dictionary({
493
 
                dbus.String("name"):
494
 
                    dbus.String(self.name, variant_level=1),
495
 
                dbus.String("fingerprint"):
496
 
                    dbus.String(self.fingerprint, variant_level=1),
497
 
                dbus.String("host"):
498
 
                    dbus.String(self.host, variant_level=1),
499
 
                dbus.String("created"):
500
 
                    _datetime_to_dbus_struct(self.created,
501
 
                                             variant_level=1),
502
 
                dbus.String("last_started"):
503
 
                    (_datetime_to_dbus_struct(self.last_started,
504
 
                                              variant_level=1)
505
 
                     if self.last_started is not None
506
 
                     else dbus.Boolean(False, variant_level=1)),
507
 
                dbus.String("started"):
508
 
                    dbus.Boolean(self.started, variant_level=1),
509
 
                dbus.String("last_checked_ok"):
510
 
                    (_datetime_to_dbus_struct(self.last_checked_ok,
511
 
                                              variant_level=1)
512
 
                     if self.last_checked_ok is not None
513
 
                     else dbus.Boolean (False, variant_level=1)),
514
 
                dbus.String("timeout"):
515
 
                    dbus.UInt64(self._timeout_milliseconds,
516
 
                                variant_level=1),
517
 
                dbus.String("interval"):
518
 
                    dbus.UInt64(self._interval_milliseconds,
519
 
                                variant_level=1),
520
 
                dbus.String("checker"):
521
 
                    dbus.String(self.checker_command,
522
 
                                variant_level=1),
523
 
                dbus.String("checker_running"):
524
 
                    dbus.Boolean(self.checker is not None,
525
 
                                 variant_level=1),
526
 
                }, signature="sv")
527
 
    
528
 
    # IsStillValid - method
529
 
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
530
 
                    (still_valid))
531
 
    IsStillValid.__name__ = "IsStillValid"
532
 
    
533
 
    # PropertyChanged - signal
534
 
    @dbus.service.signal(_interface, signature="sv")
535
 
    def PropertyChanged(self, property, value):
536
 
        "D-Bus signal"
537
 
        pass
538
 
    
539
 
    # SetChecker - method
540
 
    @dbus.service.method(_interface, in_signature="s")
541
 
    def SetChecker(self, checker):
542
 
        "D-Bus setter method"
543
 
        self.checker_command = checker
544
 
    
545
 
    # SetHost - method
546
 
    @dbus.service.method(_interface, in_signature="s")
547
 
    def SetHost(self, host):
548
 
        "D-Bus setter method"
549
 
        self.host = host
550
 
    
551
 
    # SetInterval - method
552
 
    @dbus.service.method(_interface, in_signature="t")
553
 
    def SetInterval(self, milliseconds):
554
 
        self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
555
 
    
556
 
    # SetSecret - method
557
 
    @dbus.service.method(_interface, in_signature="ay",
558
 
                         byte_arrays=True)
559
 
    def SetSecret(self, secret):
560
 
        "D-Bus setter method"
561
 
        self.secret = str(secret)
562
 
    
563
 
    # SetTimeout - method
564
 
    @dbus.service.method(_interface, in_signature="t")
565
 
    def SetTimeout(self, milliseconds):
566
 
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
567
 
    
568
 
    # Start - method
569
 
    Start = dbus.service.method(_interface)(start)
570
 
    Start.__name__ = "Start"
571
 
    
572
 
    # StartChecker - method
573
 
    @dbus.service.method(_interface)
574
 
    def StartChecker(self):
575
 
        "D-Bus method"
576
 
        self.start_checker()
577
 
    
578
 
    # Stop - method
579
 
    @dbus.service.method(_interface)
580
 
    def Stop(self):
581
 
        "D-Bus method"
582
 
        self.stop()
583
 
    
584
 
    # StopChecker - method
585
 
    StopChecker = dbus.service.method(_interface)(stop_checker)
586
 
    StopChecker.__name__ = "StopChecker"
587
 
    
588
 
    del _interface
589
383
 
590
384
 
591
385
def peer_certificate(session):
592
386
    "Return the peer's OpenPGP certificate as a bytestring"
593
387
    # If not an OpenPGP certificate...
594
 
    if (gnutls.library.functions
595
 
        .gnutls_certificate_type_get(session._c_object)
596
 
        != 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:
597
391
        # ...do the normal thing
598
392
        return session.peer_certificate
599
393
    list_size = ctypes.c_uint()
600
 
    cert_list = (gnutls.library.functions
601
 
                 .gnutls_certificate_get_peers
602
 
                 (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))
603
396
    if list_size.value == 0:
604
397
        return None
605
398
    cert = cert_list[0]
609
402
def fingerprint(openpgp):
610
403
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
611
404
    # New GnuTLS "datum" with the OpenPGP public key
612
 
    datum = (gnutls.library.types
613
 
             .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
614
 
                                         ctypes.POINTER
615
 
                                         (ctypes.c_ubyte)),
616
 
                             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)))
617
409
    # New empty GnuTLS certificate
618
410
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
619
 
    (gnutls.library.functions
620
 
     .gnutls_openpgp_crt_init(ctypes.byref(crt)))
 
411
    gnutls.library.functions.gnutls_openpgp_crt_init\
 
412
        (ctypes.byref(crt))
621
413
    # Import the OpenPGP public key into the certificate
622
 
    (gnutls.library.functions
623
 
     .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
624
 
                                gnutls.library.constants
625
 
                                .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)
626
417
    # Verify the self signature in the key
627
 
    crtverify = ctypes.c_uint()
628
 
    (gnutls.library.functions
629
 
     .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))
630
421
    if crtverify.value != 0:
631
422
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
632
423
        raise gnutls.errors.CertificateSecurityError("Verify failed")
633
424
    # New buffer for the fingerprint
634
 
    buf = ctypes.create_string_buffer(20)
635
 
    buf_len = ctypes.c_size_t()
 
425
    buffer = ctypes.create_string_buffer(20)
 
426
    buffer_length = ctypes.c_size_t()
636
427
    # Get the fingerprint from the certificate into the buffer
637
 
    (gnutls.library.functions
638
 
     .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
639
 
                                         ctypes.byref(buf_len)))
 
428
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
 
429
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
640
430
    # Deinit the certificate
641
431
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
642
432
    # Convert the buffer to a Python bytestring
643
 
    fpr = ctypes.string_at(buf, buf_len.value)
 
433
    fpr = ctypes.string_at(buffer, buffer_length.value)
644
434
    # Convert the bytestring to hexadecimal notation
645
435
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
646
436
    return hex_fpr
647
437
 
648
438
 
649
 
class TCP_handler(SocketServer.BaseRequestHandler, object):
 
439
class tcp_handler(SocketServer.BaseRequestHandler, object):
650
440
    """A TCP request handler class.
651
441
    Instantiated by IPv6_TCPServer for each request to handle it.
652
442
    Note: This will run in its own forked process."""
653
443
    
654
444
    def handle(self):
655
445
        logger.info(u"TCP connection from: %s",
656
 
                    unicode(self.client_address))
657
 
        session = (gnutls.connection
658
 
                   .ClientSession(self.request,
659
 
                                  gnutls.connection
660
 
                                  .X509Credentials()))
 
446
                     unicode(self.client_address))
 
447
        session = gnutls.connection.ClientSession\
 
448
                  (self.request, gnutls.connection.X509Credentials())
661
449
        
662
450
        line = self.request.makefile().readline()
663
451
        logger.debug(u"Protocol version: %r", line)
676
464
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
677
465
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
678
466
        #                "+DHE-DSS"))
679
 
        # Use a fallback default, since this MUST be set.
680
 
        priority = self.server.settings.get("priority", "NORMAL")
681
 
        (gnutls.library.functions
682
 
         .gnutls_priority_set_direct(session._c_object,
683
 
                                     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);
684
473
        
685
474
        try:
686
475
            session.handshake()
696
485
            session.bye()
697
486
            return
698
487
        logger.debug(u"Fingerprint: %s", fpr)
 
488
        client = None
699
489
        for c in self.server.clients:
700
490
            if c.fingerprint == fpr:
701
491
                client = c
702
492
                break
703
 
        else:
 
493
        if not client:
704
494
            logger.warning(u"Client not found for fingerprint: %s",
705
495
                           fpr)
706
496
            session.bye()
713
503
                           vars(client))
714
504
            session.bye()
715
505
            return
716
 
        ## This won't work here, since we're in a fork.
717
 
        # client.bump_timeout()
718
506
        sent_size = 0
719
507
        while sent_size < len(client.secret):
720
508
            sent = session.send(client.secret[sent_size:])
725
513
        session.bye()
726
514
 
727
515
 
728
 
class IPv6_TCPServer(SocketServer.ForkingMixIn,
729
 
                     SocketServer.TCPServer, object):
 
516
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
730
517
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
731
518
    Attributes:
732
519
        settings:       Server settings
742
529
            self.clients = kwargs["clients"]
743
530
            del kwargs["clients"]
744
531
        self.enabled = False
745
 
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
 
532
        return super(type(self), self).__init__(*args, **kwargs)
746
533
    def server_bind(self):
747
534
        """This overrides the normal server_bind() function
748
535
        to bind to an interface if one was specified, and also NOT to
777
564
#                                            if_nametoindex
778
565
#                                            (self.settings
779
566
#                                             ["interface"]))
780
 
            return super(IPv6_TCPServer, self).server_bind()
 
567
            return super(type(self), self).server_bind()
781
568
    def server_activate(self):
782
569
        if self.enabled:
783
 
            return super(IPv6_TCPServer, self).server_activate()
 
570
            return super(type(self), self).server_activate()
784
571
    def enable(self):
785
572
        self.enabled = True
786
573
 
804
591
    timevalue = datetime.timedelta(0)
805
592
    for s in interval.split():
806
593
        try:
807
 
            suffix = unicode(s[-1])
808
 
            value = int(s[:-1])
 
594
            suffix=unicode(s[-1])
 
595
            value=int(s[:-1])
809
596
            if suffix == u"d":
810
597
                delta = datetime.timedelta(value)
811
598
            elif suffix == u"s":
851
638
    """Call the C function if_nametoindex(), or equivalent"""
852
639
    global if_nametoindex
853
640
    try:
854
 
        if_nametoindex = (ctypes.cdll.LoadLibrary
855
 
                          (ctypes.util.find_library("c"))
856
 
                          .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
857
645
    except (OSError, AttributeError):
858
646
        if "struct" not in sys.modules:
859
647
            import struct
862
650
        def if_nametoindex(interface):
863
651
            "Get an interface index the hard way, i.e. using fcntl()"
864
652
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
865
 
            with closing(socket.socket()) as s:
866
 
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
867
 
                                    struct.pack("16s16x", interface))
 
653
            s = socket.socket()
 
654
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
655
                                struct.pack("16s16x", interface))
 
656
            s.close()
868
657
            interface_index = struct.unpack("I", ifreq[16:20])[0]
869
658
            return interface_index
870
659
    return if_nametoindex(interface)
894
683
 
895
684
 
896
685
def main():
 
686
    global main_loop_started
 
687
    main_loop_started = False
 
688
    
897
689
    parser = OptionParser(version = "%%prog %s" % version)
898
690
    parser.add_option("-i", "--interface", type="string",
899
691
                      metavar="IF", help="Bind to interface IF")
914
706
                      default="/etc/mandos", metavar="DIR",
915
707
                      help="Directory to search for configuration"
916
708
                      " files")
917
 
    options = parser.parse_args()[0]
 
709
    (options, args) = parser.parse_args()
918
710
    
919
711
    if options.check:
920
712
        import doctest
938
730
    # Convert the SafeConfigParser object to a dict
939
731
    server_settings = server_config.defaults()
940
732
    # Use getboolean on the boolean config option
941
 
    server_settings["debug"] = (server_config.getboolean
942
 
                                ("DEFAULT", "debug"))
 
733
    server_settings["debug"] = server_config.getboolean\
 
734
                               ("DEFAULT", "debug")
943
735
    del server_config
944
736
    
945
737
    # Override the settings from the config file with command line
959
751
        console.setLevel(logging.WARNING)
960
752
    
961
753
    if server_settings["servicename"] != "Mandos":
962
 
        syslogger.setFormatter(logging.Formatter
 
754
        syslogger.setFormatter(logging.Formatter\
963
755
                               ('Mandos (%s): %%(levelname)s:'
964
756
                                ' %%(message)s'
965
757
                                % server_settings["servicename"]))
977
769
    clients = Set()
978
770
    tcp_server = IPv6_TCPServer((server_settings["address"],
979
771
                                 server_settings["port"]),
980
 
                                TCP_handler,
 
772
                                tcp_handler,
981
773
                                settings=server_settings,
982
774
                                clients=clients)
983
775
    pidfilename = "/var/run/mandos.pid"
986
778
    except IOError, error:
987
779
        logger.error("Could not open file %r", pidfilename)
988
780
    
989
 
    try:
990
 
        uid = pwd.getpwnam("_mandos").pw_uid
991
 
    except KeyError:
992
 
        try:
993
 
            uid = pwd.getpwnam("mandos").pw_uid
994
 
        except KeyError:
995
 
            try:
996
 
                uid = pwd.getpwnam("nobody").pw_uid
997
 
            except KeyError:
998
 
                uid = 65534
999
 
    try:
1000
 
        gid = pwd.getpwnam("_mandos").pw_gid
1001
 
    except KeyError:
1002
 
        try:
1003
 
            gid = pwd.getpwnam("mandos").pw_gid
1004
 
        except KeyError:
1005
 
            try:
1006
 
                gid = pwd.getpwnam("nogroup").pw_gid
1007
 
            except KeyError:
1008
 
                gid = 65534
 
781
    uid = 65534
 
782
    gid = 65534
 
783
    try:
 
784
        uid = pwd.getpwnam("mandos").pw_uid
 
785
    except KeyError:
 
786
        try:
 
787
            uid = pwd.getpwnam("nobody").pw_uid
 
788
        except KeyError:
 
789
            pass
 
790
    try:
 
791
        gid = pwd.getpwnam("mandos").pw_gid
 
792
    except KeyError:
 
793
        try:
 
794
            gid = pwd.getpwnam("nogroup").pw_gid
 
795
        except KeyError:
 
796
            pass
1009
797
    try:
1010
798
        os.setuid(uid)
1011
799
        os.setgid(gid)
1015
803
    
1016
804
    global service
1017
805
    service = AvahiService(name = server_settings["servicename"],
1018
 
                           servicetype = "_mandos._tcp", )
 
806
                           type = "_mandos._tcp", );
1019
807
    if server_settings["interface"]:
1020
 
        service.interface = (if_nametoindex
1021
 
                             (server_settings["interface"]))
 
808
        service.interface = if_nametoindex\
 
809
                            (server_settings["interface"])
1022
810
    
1023
811
    global main_loop
1024
812
    global bus
1031
819
                                           avahi.DBUS_PATH_SERVER),
1032
820
                            avahi.DBUS_INTERFACE_SERVER)
1033
821
    # End of Avahi example code
1034
 
    bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
 
822
    
 
823
    def remove_from_clients(client):
 
824
        clients.remove(client)
 
825
        if not clients:
 
826
            logger.critical(u"No clients left, exiting")
 
827
            sys.exit()
1035
828
    
1036
829
    clients.update(Set(Client(name = section,
 
830
                              stop_hook = remove_from_clients,
1037
831
                              config
1038
832
                              = dict(client_config.items(section)))
1039
833
                       for section in client_config.sections()))
1058
852
        pidfile.write(str(pid) + "\n")
1059
853
        pidfile.close()
1060
854
        del pidfile
1061
 
    except IOError:
 
855
    except IOError, err:
1062
856
        logger.error(u"Could not write to file %r with PID %d",
1063
857
                     pidfilename, pid)
1064
858
    except NameError:
1087
881
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1088
882
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1089
883
    
1090
 
    class MandosServer(dbus.service.Object):
1091
 
        """A D-Bus proxy object"""
1092
 
        def __init__(self):
1093
 
            dbus.service.Object.__init__(self, bus,
1094
 
                                         "/Mandos")
1095
 
        _interface = u"org.mandos_system.Mandos"
1096
 
        
1097
 
        @dbus.service.signal(_interface, signature="oa{sv}")
1098
 
        def ClientAdded(self, objpath, properties):
1099
 
            "D-Bus signal"
1100
 
            pass
1101
 
        
1102
 
        @dbus.service.signal(_interface, signature="o")
1103
 
        def ClientRemoved(self, objpath):
1104
 
            "D-Bus signal"
1105
 
            pass
1106
 
        
1107
 
        @dbus.service.method(_interface, out_signature="ao")
1108
 
        def GetAllClients(self):
1109
 
            return dbus.Array(c.dbus_object_path for c in clients)
1110
 
        
1111
 
        @dbus.service.method(_interface, out_signature="a{oa{sv}}")
1112
 
        def GetAllClientsWithProperties(self):
1113
 
            return dbus.Dictionary(
1114
 
                ((c.dbus_object_path, c.GetAllProperties())
1115
 
                 for c in clients),
1116
 
                signature="oa{sv}")
1117
 
        
1118
 
        @dbus.service.method(_interface, in_signature="o")
1119
 
        def RemoveClient(self, object_path):
1120
 
            for c in clients:
1121
 
                if c.dbus_object_path == object_path:
1122
 
                    c.stop()
1123
 
                    clients.remove(c)
1124
 
                    return
1125
 
            raise KeyError
1126
 
        
1127
 
        del _interface
1128
 
    
1129
 
    mandos_server = MandosServer()
1130
 
    
1131
884
    for client in clients:
1132
 
        # Emit D-Bus signal
1133
 
        mandos_server.ClientAdded(client.dbus_object_path,
1134
 
                                  client.GetAllProperties())
1135
885
        client.start()
1136
886
    
1137
887
    tcp_server.enable()
1156
906
        
1157
907
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
1158
908
                             lambda *args, **kwargs:
1159
 
                             (tcp_server.handle_request
1160
 
                              (*args[2:], **kwargs) or True))
 
909
                             tcp_server.handle_request\
 
910
                             (*args[2:], **kwargs) or True)
1161
911
        
1162
912
        logger.debug(u"Starting main loop")
 
913
        main_loop_started = True
1163
914
        main_loop.run()
1164
915
    except AvahiError, error:
1165
916
        logger.critical(u"AvahiError: %s" + unicode(error))