/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2008-10-03 09:32:30 UTC
  • Revision ID: teddy@fukt.bsnet.se-20081003093230-rshn19e0c19zz12i
* .bzrignore (plugins.d/askpass-fifo): Added.

* Makefile (FORTIFY): Added "-fstack-protector-all".
  (mandos, mandos-keygen): Use more strict regexps when updating the
                           version number.

* mandos (Client.__init__): Use os.path.expandvars() and
                            os.path.expanduser() on the "secfile"
                            config value.

* plugins.d/splashy.c: Update comments and order of #include's.
  (main): Check user and group when looking for running splashy
          process.  Do not ignore ENOENT from execl().  Use _exit()
          instead of "return" when an error happens in child
          processes.  Bug fix: Only wait for splashy_update
          completion if it was started.  Bug fix: detect failing
          waitpid().  Only kill splashy_update if it is running.  Do
          the killing of the old splashy process before the fork().
          Do setsid() and setuid(geteuid()) before starting the new
          splashy.  Report failing execl().

* plugins.d/usplash.c: Update comments and order of #include's.
  (main): Check user and group when looking for running usplash
          process.  Do not report execv() error if interrupted by a
          signal.

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 © 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
56
55
import logging
57
56
import logging.handlers
58
57
import pwd
59
 
from contextlib import closing
60
58
 
61
59
import dbus
62
 
import dbus.service
63
60
import gobject
64
61
import avahi
65
62
from dbus.mainloop.glib import DBusGMainLoop
66
63
import ctypes
67
64
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()
112
109
                  a sensible number of times
113
110
    """
114
111
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
 
                 servicetype = None, port = None, TXT = None,
116
 
                 domain = "", host = "", max_renames = 32768):
 
112
                 servicetype = None, port = None, TXT = None, domain = "",
 
113
                 host = "", max_renames = 32768):
117
114
        self.interface = interface
118
115
        self.name = name
119
116
        self.type = servicetype
120
117
        self.port = port
121
 
        self.TXT = TXT if TXT is not None else []
 
118
        if TXT is None:
 
119
            self.TXT = []
 
120
        else:
 
121
            self.TXT = TXT
122
122
        self.domain = domain
123
123
        self.host = host
124
124
        self.rename_count = 0
133
133
        self.name = server.GetAlternativeServiceName(self.name)
134
134
        logger.info(u"Changing Zeroconf service name to %r ...",
135
135
                    str(self.name))
136
 
        syslogger.setFormatter(logging.Formatter
 
136
        syslogger.setFormatter(logging.Formatter\
137
137
                               ('Mandos (%s): %%(levelname)s:'
138
 
                                ' %%(message)s' % self.name))
 
138
                               ' %%(message)s' % self.name))
139
139
        self.remove()
140
140
        self.add()
141
141
        self.rename_count += 1
147
147
        """Derived from the Avahi example code"""
148
148
        global group
149
149
        if group is None:
150
 
            group = dbus.Interface(bus.get_object
151
 
                                   (avahi.DBUS_NAME,
 
150
            group = dbus.Interface\
 
151
                    (bus.get_object(avahi.DBUS_NAME,
152
152
                                    server.EntryGroupNew()),
153
 
                                   avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
153
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
154
154
            group.connect_to_signal('StateChanged',
155
155
                                    entry_group_state_changed)
156
156
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
170
170
# End of Avahi example code
171
171
 
172
172
 
173
 
def _datetime_to_dbus(dt, variant_level=0):
174
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
175
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
176
 
 
177
 
 
178
 
class Client(dbus.service.Object):
 
173
class Client(object):
179
174
    """A representation of a client host served by this server.
180
175
    Attributes:
181
 
    name:       string; from the config file, used in log messages
 
176
    name:      string; from the config file, used in log messages
182
177
    fingerprint: string (40 or 32 hexadecimal digits); used to
183
178
                 uniquely identify the client
184
 
    secret:     bytestring; sent verbatim (over TLS) to client
185
 
    host:       string; available for use by the checker command
186
 
    created:    datetime.datetime(); (UTC) object creation
187
 
    last_enabled: datetime.datetime(); (UTC)
188
 
    enabled:    bool()
189
 
    last_checked_ok: datetime.datetime(); (UTC) or None
190
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
191
 
                                      until this client is invalid
192
 
    interval:   datetime.timedelta(); How often to start a new checker
193
 
    disable_hook:  If set, called by disable() as disable_hook(self)
194
 
    checker:    subprocess.Popen(); a running checker process used
195
 
                                    to see if the client lives.
196
 
                                    'None' if no process is running.
 
179
    secret:    bytestring; sent verbatim (over TLS) to client
 
180
    host:      string; available for use by the checker command
 
181
    created:   datetime.datetime(); object creation, not client host
 
182
    last_checked_ok: datetime.datetime() or None if not yet checked OK
 
183
    timeout:   datetime.timedelta(); How long from last_checked_ok
 
184
                                     until this client is invalid
 
185
    interval:  datetime.timedelta(); How often to start a new checker
 
186
    stop_hook: If set, called by stop() as stop_hook(self)
 
187
    checker:   subprocess.Popen(); a running checker process used
 
188
                                   to see if the client lives.
 
189
                                   'None' if no process is running.
197
190
    checker_initiator_tag: a gobject event source tag, or None
198
 
    disable_initiator_tag:    - '' -
 
191
    stop_initiator_tag:    - '' -
199
192
    checker_callback_tag:  - '' -
200
193
    checker_command: string; External command which is run to check if
201
194
                     client lives.  %() expansions are done at
202
195
                     runtime with vars(self) as dict, so that for
203
196
                     instance %(name)s can be used in the command.
204
 
    dbus_object_path: dbus.ObjectPath
205
197
    Private attibutes:
206
198
    _timeout: Real variable for 'timeout'
207
199
    _interval: Real variable for 'interval'
209
201
    _interval_milliseconds: - '' -
210
202
    """
211
203
    def _set_timeout(self, timeout):
212
 
        "Setter function for the 'timeout' attribute"
 
204
        "Setter function for 'timeout' attribute"
213
205
        self._timeout = timeout
214
206
        self._timeout_milliseconds = ((self.timeout.days
215
207
                                       * 24 * 60 * 60 * 1000)
216
208
                                      + (self.timeout.seconds * 1000)
217
209
                                      + (self.timeout.microseconds
218
210
                                         // 1000))
219
 
        # Emit D-Bus signal
220
 
        self.PropertyChanged(dbus.String(u"timeout"),
221
 
                             (dbus.UInt64(self._timeout_milliseconds,
222
 
                                          variant_level=1)))
223
 
    timeout = property(lambda self: self._timeout, _set_timeout)
 
211
    timeout = property(lambda self: self._timeout,
 
212
                       _set_timeout)
224
213
    del _set_timeout
225
 
    
226
214
    def _set_interval(self, interval):
227
 
        "Setter function for the 'interval' attribute"
 
215
        "Setter function for 'interval' attribute"
228
216
        self._interval = interval
229
217
        self._interval_milliseconds = ((self.interval.days
230
218
                                        * 24 * 60 * 60 * 1000)
232
220
                                          * 1000)
233
221
                                       + (self.interval.microseconds
234
222
                                          // 1000))
235
 
        # Emit D-Bus signal
236
 
        self.PropertyChanged(dbus.String(u"interval"),
237
 
                             (dbus.UInt64(self._interval_milliseconds,
238
 
                                          variant_level=1)))
239
 
    interval = property(lambda self: self._interval, _set_interval)
 
223
    interval = property(lambda self: self._interval,
 
224
                        _set_interval)
240
225
    del _set_interval
241
 
    
242
 
    def __init__(self, name = None, disable_hook=None, config=None):
 
226
    def __init__(self, name = None, stop_hook=None, config=None):
243
227
        """Note: the 'checker' key in 'config' sets the
244
228
        'checker_command' attribute and *not* the 'checker'
245
229
        attribute."""
246
 
        self.dbus_object_path = (dbus.ObjectPath
247
 
                                 ("/Mandos/clients/"
248
 
                                  + name.replace(".", "_")))
249
 
        dbus.service.Object.__init__(self, bus,
250
 
                                     self.dbus_object_path)
251
230
        if config is None:
252
231
            config = {}
253
232
        self.name = name
255
234
        # Uppercase and remove spaces from fingerprint for later
256
235
        # comparison purposes with return value from the fingerprint()
257
236
        # function
258
 
        self.fingerprint = (config["fingerprint"].upper()
259
 
                            .replace(u" ", u""))
 
237
        self.fingerprint = config["fingerprint"].upper()\
 
238
                           .replace(u" ", u"")
260
239
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
261
240
        if "secret" in config:
262
241
            self.secret = config["secret"].decode(u"base64")
263
242
        elif "secfile" in config:
264
 
            with closing(open(os.path.expanduser
265
 
                              (os.path.expandvars
266
 
                               (config["secfile"])))) as secfile:
267
 
                self.secret = secfile.read()
 
243
            secfile = open(os.path.expanduser(os.path.expandvars
 
244
                                              (config["secfile"])))
 
245
            self.secret = secfile.read()
 
246
            secfile.close()
268
247
        else:
269
248
            raise TypeError(u"No secret or secfile for client %s"
270
249
                            % self.name)
271
250
        self.host = config.get("host", "")
272
 
        self.created = datetime.datetime.utcnow()
273
 
        self.enabled = False
274
 
        self.last_enabled = None
 
251
        self.created = datetime.datetime.now()
275
252
        self.last_checked_ok = None
276
253
        self.timeout = string_to_delta(config["timeout"])
277
254
        self.interval = string_to_delta(config["interval"])
278
 
        self.disable_hook = disable_hook
 
255
        self.stop_hook = stop_hook
279
256
        self.checker = None
280
257
        self.checker_initiator_tag = None
281
 
        self.disable_initiator_tag = None
 
258
        self.stop_initiator_tag = None
282
259
        self.checker_callback_tag = None
283
 
        self.checker_command = config["checker"]
284
 
    
285
 
    def enable(self):
 
260
        self.check_command = config["checker"]
 
261
    def start(self):
286
262
        """Start this client's checker and timeout hooks"""
287
 
        self.last_enabled = datetime.datetime.utcnow()
288
263
        # Schedule a new checker to be started an 'interval' from now,
289
264
        # and every interval from then on.
290
 
        self.checker_initiator_tag = (gobject.timeout_add
291
 
                                      (self._interval_milliseconds,
292
 
                                       self.start_checker))
 
265
        self.checker_initiator_tag = gobject.timeout_add\
 
266
                                     (self._interval_milliseconds,
 
267
                                      self.start_checker)
293
268
        # Also start a new checker *right now*.
294
269
        self.start_checker()
295
 
        # Schedule a disable() when 'timeout' has passed
296
 
        self.disable_initiator_tag = (gobject.timeout_add
297
 
                                   (self._timeout_milliseconds,
298
 
                                    self.disable))
299
 
        self.enabled = True
300
 
        # Emit D-Bus signal
301
 
        self.PropertyChanged(dbus.String(u"enabled"),
302
 
                             dbus.Boolean(True, variant_level=1))
303
 
        self.PropertyChanged(dbus.String(u"last_enabled"),
304
 
                             (_datetime_to_dbus(self.last_enabled,
305
 
                                                variant_level=1)))
306
 
    
307
 
    def disable(self):
308
 
        """Disable this client."""
309
 
        if not getattr(self, "enabled", False):
 
270
        # Schedule a stop() when 'timeout' has passed
 
271
        self.stop_initiator_tag = gobject.timeout_add\
 
272
                                  (self._timeout_milliseconds,
 
273
                                   self.stop)
 
274
    def stop(self):
 
275
        """Stop this client.
 
276
        The possibility that a client might be restarted is left open,
 
277
        but not currently used."""
 
278
        # If this client doesn't have a secret, it is already stopped.
 
279
        if hasattr(self, "secret") and self.secret:
 
280
            logger.info(u"Stopping client %s", self.name)
 
281
            self.secret = None
 
282
        else:
310
283
            return False
311
 
        logger.info(u"Disabling client %s", self.name)
312
 
        if getattr(self, "disable_initiator_tag", False):
313
 
            gobject.source_remove(self.disable_initiator_tag)
314
 
            self.disable_initiator_tag = None
 
284
        if getattr(self, "stop_initiator_tag", False):
 
285
            gobject.source_remove(self.stop_initiator_tag)
 
286
            self.stop_initiator_tag = None
315
287
        if getattr(self, "checker_initiator_tag", False):
316
288
            gobject.source_remove(self.checker_initiator_tag)
317
289
            self.checker_initiator_tag = None
318
290
        self.stop_checker()
319
 
        if self.disable_hook:
320
 
            self.disable_hook(self)
321
 
        self.enabled = False
322
 
        # Emit D-Bus signal
323
 
        self.PropertyChanged(dbus.String(u"enabled"),
324
 
                             dbus.Boolean(False, variant_level=1))
 
291
        if self.stop_hook:
 
292
            self.stop_hook(self)
325
293
        # Do not run this again if called by a gobject.timeout_add
326
294
        return False
327
 
    
328
295
    def __del__(self):
329
 
        self.disable_hook = None
330
 
        self.disable()
331
 
    
332
 
    def checker_callback(self, pid, condition, command):
 
296
        self.stop_hook = None
 
297
        self.stop()
 
298
    def checker_callback(self, pid, condition):
333
299
        """The checker has completed, so take appropriate actions."""
 
300
        now = datetime.datetime.now()
334
301
        self.checker_callback_tag = None
335
302
        self.checker = None
336
 
        # Emit D-Bus signal
337
 
        self.PropertyChanged(dbus.String(u"checker_running"),
338
 
                             dbus.Boolean(False, variant_level=1))
339
 
        if (os.WIFEXITED(condition)
340
 
            and (os.WEXITSTATUS(condition) == 0)):
 
303
        if os.WIFEXITED(condition) \
 
304
               and (os.WEXITSTATUS(condition) == 0):
341
305
            logger.info(u"Checker for %(name)s succeeded",
342
306
                        vars(self))
343
 
            # Emit D-Bus signal
344
 
            self.CheckerCompleted(dbus.Boolean(True),
345
 
                                  dbus.UInt16(condition),
346
 
                                  dbus.String(command))
347
 
            self.bump_timeout()
 
307
            self.last_checked_ok = now
 
308
            gobject.source_remove(self.stop_initiator_tag)
 
309
            self.stop_initiator_tag = gobject.timeout_add\
 
310
                                      (self._timeout_milliseconds,
 
311
                                       self.stop)
348
312
        elif not os.WIFEXITED(condition):
349
313
            logger.warning(u"Checker for %(name)s crashed?",
350
314
                           vars(self))
351
 
            # Emit D-Bus signal
352
 
            self.CheckerCompleted(dbus.Boolean(False),
353
 
                                  dbus.UInt16(condition),
354
 
                                  dbus.String(command))
355
315
        else:
356
316
            logger.info(u"Checker for %(name)s failed",
357
317
                        vars(self))
358
 
            # Emit D-Bus signal
359
 
            self.CheckerCompleted(dbus.Boolean(False),
360
 
                                  dbus.UInt16(condition),
361
 
                                  dbus.String(command))
362
 
    
363
 
    def bump_timeout(self):
364
 
        """Bump up the timeout for this client.
365
 
        This should only be called when the client has been seen,
366
 
        alive and well.
367
 
        """
368
 
        self.last_checked_ok = datetime.datetime.utcnow()
369
 
        gobject.source_remove(self.disable_initiator_tag)
370
 
        self.disable_initiator_tag = (gobject.timeout_add
371
 
                                      (self._timeout_milliseconds,
372
 
                                       self.disable))
373
 
        self.PropertyChanged(dbus.String(u"last_checked_ok"),
374
 
                             (_datetime_to_dbus(self.last_checked_ok,
375
 
                                                variant_level=1)))
376
 
    
377
318
    def start_checker(self):
378
319
        """Start a new checker subprocess if one is not running.
379
320
        If a checker already exists, leave it running and do
388
329
        # is as it should be.
389
330
        if self.checker is None:
390
331
            try:
391
 
                # In case checker_command has exactly one % operator
392
 
                command = self.checker_command % self.host
 
332
                # In case check_command has exactly one % operator
 
333
                command = self.check_command % self.host
393
334
            except TypeError:
394
335
                # Escape attributes for the shell
395
336
                escaped_attrs = dict((key, re.escape(str(val)))
396
337
                                     for key, val in
397
338
                                     vars(self).iteritems())
398
339
                try:
399
 
                    command = self.checker_command % escaped_attrs
 
340
                    command = self.check_command % escaped_attrs
400
341
                except TypeError, error:
401
342
                    logger.error(u'Could not format string "%s":'
402
 
                                 u' %s', self.checker_command, error)
 
343
                                 u' %s', self.check_command, error)
403
344
                    return True # Try again later
404
345
            try:
405
346
                logger.info(u"Starting checker %r for %s",
411
352
                self.checker = subprocess.Popen(command,
412
353
                                                close_fds=True,
413
354
                                                shell=True, cwd="/")
414
 
                # Emit D-Bus signal
415
 
                self.CheckerStarted(command)
416
 
                self.PropertyChanged(dbus.String("checker_running"),
417
 
                                     dbus.Boolean(True, variant_level=1))
418
 
                self.checker_callback_tag = (gobject.child_watch_add
419
 
                                             (self.checker.pid,
420
 
                                              self.checker_callback,
421
 
                                              data=command))
 
355
                self.checker_callback_tag = gobject.child_watch_add\
 
356
                                            (self.checker.pid,
 
357
                                             self.checker_callback)
422
358
            except OSError, error:
423
359
                logger.error(u"Failed to start subprocess: %s",
424
360
                             error)
425
361
        # Re-run this periodically if run by gobject.timeout_add
426
362
        return True
427
 
    
428
363
    def stop_checker(self):
429
364
        """Force the checker process, if any, to stop."""
430
365
        if self.checker_callback_tag:
442
377
            if error.errno != errno.ESRCH: # No such process
443
378
                raise
444
379
        self.checker = None
445
 
        self.PropertyChanged(dbus.String(u"checker_running"),
446
 
                             dbus.Boolean(False, variant_level=1))
447
 
    
448
380
    def still_valid(self):
449
381
        """Has the timeout not yet passed for this client?"""
450
 
        if not getattr(self, "enabled", False):
451
 
            return False
452
 
        now = datetime.datetime.utcnow()
 
382
        now = datetime.datetime.now()
453
383
        if self.last_checked_ok is None:
454
384
            return now < (self.created + self.timeout)
455
385
        else:
456
386
            return now < (self.last_checked_ok + self.timeout)
457
 
    
458
 
    ## D-Bus methods & signals
459
 
    _interface = u"org.mandos_system.Mandos.Client"
460
 
    
461
 
    # BumpTimeout - method
462
 
    BumpTimeout = dbus.service.method(_interface)(bump_timeout)
463
 
    BumpTimeout.__name__ = "BumpTimeout"
464
 
    
465
 
    # CheckerCompleted - signal
466
 
    @dbus.service.signal(_interface, signature="bqs")
467
 
    def CheckerCompleted(self, success, condition, command):
468
 
        "D-Bus signal"
469
 
        pass
470
 
    
471
 
    # CheckerStarted - signal
472
 
    @dbus.service.signal(_interface, signature="s")
473
 
    def CheckerStarted(self, command):
474
 
        "D-Bus signal"
475
 
        pass
476
 
    
477
 
    # GetAllProperties - method
478
 
    @dbus.service.method(_interface, out_signature="a{sv}")
479
 
    def GetAllProperties(self):
480
 
        "D-Bus method"
481
 
        return dbus.Dictionary({
482
 
                dbus.String("name"):
483
 
                    dbus.String(self.name, variant_level=1),
484
 
                dbus.String("fingerprint"):
485
 
                    dbus.String(self.fingerprint, variant_level=1),
486
 
                dbus.String("host"):
487
 
                    dbus.String(self.host, variant_level=1),
488
 
                dbus.String("created"):
489
 
                    _datetime_to_dbus(self.created, variant_level=1),
490
 
                dbus.String("last_enabled"):
491
 
                    (_datetime_to_dbus(self.last_enabled,
492
 
                                       variant_level=1)
493
 
                     if self.last_enabled is not None
494
 
                     else dbus.Boolean(False, variant_level=1)),
495
 
                dbus.String("enabled"):
496
 
                    dbus.Boolean(self.enabled, variant_level=1),
497
 
                dbus.String("last_checked_ok"):
498
 
                    (_datetime_to_dbus(self.last_checked_ok,
499
 
                                       variant_level=1)
500
 
                     if self.last_checked_ok is not None
501
 
                     else dbus.Boolean (False, variant_level=1)),
502
 
                dbus.String("timeout"):
503
 
                    dbus.UInt64(self._timeout_milliseconds,
504
 
                                variant_level=1),
505
 
                dbus.String("interval"):
506
 
                    dbus.UInt64(self._interval_milliseconds,
507
 
                                variant_level=1),
508
 
                dbus.String("checker"):
509
 
                    dbus.String(self.checker_command,
510
 
                                variant_level=1),
511
 
                dbus.String("checker_running"):
512
 
                    dbus.Boolean(self.checker is not None,
513
 
                                 variant_level=1),
514
 
                }, signature="sv")
515
 
    
516
 
    # IsStillValid - method
517
 
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
518
 
                    (still_valid))
519
 
    IsStillValid.__name__ = "IsStillValid"
520
 
    
521
 
    # PropertyChanged - signal
522
 
    @dbus.service.signal(_interface, signature="sv")
523
 
    def PropertyChanged(self, property, value):
524
 
        "D-Bus signal"
525
 
        pass
526
 
    
527
 
    # SetChecker - method
528
 
    @dbus.service.method(_interface, in_signature="s")
529
 
    def SetChecker(self, checker):
530
 
        "D-Bus setter method"
531
 
        self.checker_command = checker
532
 
    
533
 
    # SetHost - method
534
 
    @dbus.service.method(_interface, in_signature="s")
535
 
    def SetHost(self, host):
536
 
        "D-Bus setter method"
537
 
        self.host = host
538
 
    
539
 
    # SetInterval - method
540
 
    @dbus.service.method(_interface, in_signature="t")
541
 
    def SetInterval(self, milliseconds):
542
 
        self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
543
 
    
544
 
    # SetSecret - method
545
 
    @dbus.service.method(_interface, in_signature="ay",
546
 
                         byte_arrays=True)
547
 
    def SetSecret(self, secret):
548
 
        "D-Bus setter method"
549
 
        self.secret = str(secret)
550
 
    
551
 
    # SetTimeout - method
552
 
    @dbus.service.method(_interface, in_signature="t")
553
 
    def SetTimeout(self, milliseconds):
554
 
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
555
 
    
556
 
    # Enable - method
557
 
    Enable = dbus.service.method(_interface)(enable)
558
 
    Enable.__name__ = "Enable"
559
 
    
560
 
    # StartChecker - method
561
 
    @dbus.service.method(_interface)
562
 
    def StartChecker(self):
563
 
        "D-Bus method"
564
 
        self.start_checker()
565
 
    
566
 
    # Disable - method
567
 
    @dbus.service.method(_interface)
568
 
    def Disable(self):
569
 
        "D-Bus method"
570
 
        self.disable()
571
 
    
572
 
    # StopChecker - method
573
 
    StopChecker = dbus.service.method(_interface)(stop_checker)
574
 
    StopChecker.__name__ = "StopChecker"
575
 
    
576
 
    del _interface
577
387
 
578
388
 
579
389
def peer_certificate(session):
580
390
    "Return the peer's OpenPGP certificate as a bytestring"
581
391
    # If not an OpenPGP certificate...
582
 
    if (gnutls.library.functions
583
 
        .gnutls_certificate_type_get(session._c_object)
584
 
        != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
392
    if gnutls.library.functions.gnutls_certificate_type_get\
 
393
            (session._c_object) \
 
394
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
585
395
        # ...do the normal thing
586
396
        return session.peer_certificate
587
397
    list_size = ctypes.c_uint()
588
 
    cert_list = (gnutls.library.functions
589
 
                 .gnutls_certificate_get_peers
590
 
                 (session._c_object, ctypes.byref(list_size)))
 
398
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
 
399
        (session._c_object, ctypes.byref(list_size))
591
400
    if list_size.value == 0:
592
401
        return None
593
402
    cert = cert_list[0]
597
406
def fingerprint(openpgp):
598
407
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
599
408
    # New GnuTLS "datum" with the OpenPGP public key
600
 
    datum = (gnutls.library.types
601
 
             .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
602
 
                                         ctypes.POINTER
603
 
                                         (ctypes.c_ubyte)),
604
 
                             ctypes.c_uint(len(openpgp))))
 
409
    datum = gnutls.library.types.gnutls_datum_t\
 
410
        (ctypes.cast(ctypes.c_char_p(openpgp),
 
411
                     ctypes.POINTER(ctypes.c_ubyte)),
 
412
         ctypes.c_uint(len(openpgp)))
605
413
    # New empty GnuTLS certificate
606
414
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
607
 
    (gnutls.library.functions
608
 
     .gnutls_openpgp_crt_init(ctypes.byref(crt)))
 
415
    gnutls.library.functions.gnutls_openpgp_crt_init\
 
416
        (ctypes.byref(crt))
609
417
    # Import the OpenPGP public key into the certificate
610
 
    (gnutls.library.functions
611
 
     .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
612
 
                                gnutls.library.constants
613
 
                                .GNUTLS_OPENPGP_FMT_RAW))
 
418
    gnutls.library.functions.gnutls_openpgp_crt_import\
 
419
                    (crt, ctypes.byref(datum),
 
420
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
614
421
    # Verify the self signature in the key
615
422
    crtverify = ctypes.c_uint()
616
 
    (gnutls.library.functions
617
 
     .gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
 
423
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
 
424
        (crt, 0, ctypes.byref(crtverify))
618
425
    if crtverify.value != 0:
619
426
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
620
427
        raise gnutls.errors.CertificateSecurityError("Verify failed")
622
429
    buf = ctypes.create_string_buffer(20)
623
430
    buf_len = ctypes.c_size_t()
624
431
    # Get the fingerprint from the certificate into the buffer
625
 
    (gnutls.library.functions
626
 
     .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
627
 
                                         ctypes.byref(buf_len)))
 
432
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
 
433
        (crt, ctypes.byref(buf), ctypes.byref(buf_len))
628
434
    # Deinit the certificate
629
435
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
630
436
    # Convert the buffer to a Python bytestring
641
447
    
642
448
    def handle(self):
643
449
        logger.info(u"TCP connection from: %s",
644
 
                    unicode(self.client_address))
645
 
        session = (gnutls.connection
646
 
                   .ClientSession(self.request,
647
 
                                  gnutls.connection
648
 
                                  .X509Credentials()))
 
450
                     unicode(self.client_address))
 
451
        session = gnutls.connection.ClientSession\
 
452
                  (self.request, gnutls.connection.X509Credentials())
649
453
        
650
454
        line = self.request.makefile().readline()
651
455
        logger.debug(u"Protocol version: %r", line)
664
468
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
665
469
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
666
470
        #                "+DHE-DSS"))
667
 
        # Use a fallback default, since this MUST be set.
668
 
        priority = self.server.settings.get("priority", "NORMAL")
669
 
        (gnutls.library.functions
670
 
         .gnutls_priority_set_direct(session._c_object,
671
 
                                     priority, None))
 
471
        priority = "NORMAL"             # Fallback default, since this
 
472
                                        # MUST be set.
 
473
        if self.server.settings["priority"]:
 
474
            priority = self.server.settings["priority"]
 
475
        gnutls.library.functions.gnutls_priority_set_direct\
 
476
            (session._c_object, priority, None)
672
477
        
673
478
        try:
674
479
            session.handshake()
684
489
            session.bye()
685
490
            return
686
491
        logger.debug(u"Fingerprint: %s", fpr)
 
492
        client = None
687
493
        for c in self.server.clients:
688
494
            if c.fingerprint == fpr:
689
495
                client = c
690
496
                break
691
 
        else:
 
497
        if not client:
692
498
            logger.warning(u"Client not found for fingerprint: %s",
693
499
                           fpr)
694
500
            session.bye()
701
507
                           vars(client))
702
508
            session.bye()
703
509
            return
704
 
        ## This won't work here, since we're in a fork.
705
 
        # client.bump_timeout()
706
510
        sent_size = 0
707
511
        while sent_size < len(client.secret):
708
512
            sent = session.send(client.secret[sent_size:])
713
517
        session.bye()
714
518
 
715
519
 
716
 
class IPv6_TCPServer(SocketServer.ForkingMixIn,
717
 
                     SocketServer.TCPServer, object):
 
520
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
718
521
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
719
522
    Attributes:
720
523
        settings:       Server settings
839
642
    """Call the C function if_nametoindex(), or equivalent"""
840
643
    global if_nametoindex
841
644
    try:
842
 
        if_nametoindex = (ctypes.cdll.LoadLibrary
843
 
                          (ctypes.util.find_library("c"))
844
 
                          .if_nametoindex)
 
645
        if_nametoindex = ctypes.cdll.LoadLibrary\
 
646
            (ctypes.util.find_library("c")).if_nametoindex
845
647
    except (OSError, AttributeError):
846
648
        if "struct" not in sys.modules:
847
649
            import struct
850
652
        def if_nametoindex(interface):
851
653
            "Get an interface index the hard way, i.e. using fcntl()"
852
654
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
853
 
            with closing(socket.socket()) as s:
854
 
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
855
 
                                    struct.pack("16s16x", interface))
 
655
            s = socket.socket()
 
656
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
657
                                struct.pack("16s16x", interface))
 
658
            s.close()
856
659
            interface_index = struct.unpack("I", ifreq[16:20])[0]
857
660
            return interface_index
858
661
    return if_nametoindex(interface)
926
729
    # Convert the SafeConfigParser object to a dict
927
730
    server_settings = server_config.defaults()
928
731
    # Use getboolean on the boolean config option
929
 
    server_settings["debug"] = (server_config.getboolean
930
 
                                ("DEFAULT", "debug"))
 
732
    server_settings["debug"] = server_config.getboolean\
 
733
                               ("DEFAULT", "debug")
931
734
    del server_config
932
735
    
933
736
    # Override the settings from the config file with command line
947
750
        console.setLevel(logging.WARNING)
948
751
    
949
752
    if server_settings["servicename"] != "Mandos":
950
 
        syslogger.setFormatter(logging.Formatter
 
753
        syslogger.setFormatter(logging.Formatter\
951
754
                               ('Mandos (%s): %%(levelname)s:'
952
755
                                ' %%(message)s'
953
756
                                % server_settings["servicename"]))
974
777
    except IOError, error:
975
778
        logger.error("Could not open file %r", pidfilename)
976
779
    
977
 
    try:
978
 
        uid = pwd.getpwnam("_mandos").pw_uid
979
 
    except KeyError:
980
 
        try:
981
 
            uid = pwd.getpwnam("mandos").pw_uid
982
 
        except KeyError:
983
 
            try:
984
 
                uid = pwd.getpwnam("nobody").pw_uid
985
 
            except KeyError:
986
 
                uid = 65534
987
 
    try:
988
 
        gid = pwd.getpwnam("_mandos").pw_gid
989
 
    except KeyError:
990
 
        try:
991
 
            gid = pwd.getpwnam("mandos").pw_gid
992
 
        except KeyError:
993
 
            try:
994
 
                gid = pwd.getpwnam("nogroup").pw_gid
995
 
            except KeyError:
996
 
                gid = 65534
 
780
    uid = 65534
 
781
    gid = 65534
 
782
    try:
 
783
        uid = pwd.getpwnam("mandos").pw_uid
 
784
    except KeyError:
 
785
        try:
 
786
            uid = pwd.getpwnam("nobody").pw_uid
 
787
        except KeyError:
 
788
            pass
 
789
    try:
 
790
        gid = pwd.getpwnam("mandos").pw_gid
 
791
    except KeyError:
 
792
        try:
 
793
            gid = pwd.getpwnam("nogroup").pw_gid
 
794
        except KeyError:
 
795
            pass
997
796
    try:
998
797
        os.setuid(uid)
999
798
        os.setgid(gid)
1005
804
    service = AvahiService(name = server_settings["servicename"],
1006
805
                           servicetype = "_mandos._tcp", )
1007
806
    if server_settings["interface"]:
1008
 
        service.interface = (if_nametoindex
1009
 
                             (server_settings["interface"]))
 
807
        service.interface = if_nametoindex\
 
808
                            (server_settings["interface"])
1010
809
    
1011
810
    global main_loop
1012
811
    global bus
1019
818
                                           avahi.DBUS_PATH_SERVER),
1020
819
                            avahi.DBUS_INTERFACE_SERVER)
1021
820
    # End of Avahi example code
1022
 
    bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
 
821
    
 
822
    def remove_from_clients(client):
 
823
        clients.remove(client)
 
824
        if not clients:
 
825
            logger.critical(u"No clients left, exiting")
 
826
            sys.exit()
1023
827
    
1024
828
    clients.update(Set(Client(name = section,
 
829
                              stop_hook = remove_from_clients,
1025
830
                              config
1026
831
                              = dict(client_config.items(section)))
1027
832
                       for section in client_config.sections()))
1065
870
        
1066
871
        while clients:
1067
872
            client = clients.pop()
1068
 
            client.disable_hook = None
1069
 
            client.disable()
 
873
            client.stop_hook = None
 
874
            client.stop()
1070
875
    
1071
876
    atexit.register(cleanup)
1072
877
    
1075
880
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1076
881
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1077
882
    
1078
 
    class MandosServer(dbus.service.Object):
1079
 
        """A D-Bus proxy object"""
1080
 
        def __init__(self):
1081
 
            dbus.service.Object.__init__(self, bus,
1082
 
                                         "/Mandos")
1083
 
        _interface = u"org.mandos_system.Mandos"
1084
 
        
1085
 
        @dbus.service.signal(_interface, signature="oa{sv}")
1086
 
        def ClientAdded(self, objpath, properties):
1087
 
            "D-Bus signal"
1088
 
            pass
1089
 
        
1090
 
        @dbus.service.signal(_interface, signature="o")
1091
 
        def ClientRemoved(self, objpath):
1092
 
            "D-Bus signal"
1093
 
            pass
1094
 
        
1095
 
        @dbus.service.method(_interface, out_signature="ao")
1096
 
        def GetAllClients(self):
1097
 
            return dbus.Array(c.dbus_object_path for c in clients)
1098
 
        
1099
 
        @dbus.service.method(_interface, out_signature="a{oa{sv}}")
1100
 
        def GetAllClientsWithProperties(self):
1101
 
            return dbus.Dictionary(
1102
 
                ((c.dbus_object_path, c.GetAllProperties())
1103
 
                 for c in clients),
1104
 
                signature="oa{sv}")
1105
 
        
1106
 
        @dbus.service.method(_interface, in_signature="o")
1107
 
        def RemoveClient(self, object_path):
1108
 
            for c in clients:
1109
 
                if c.dbus_object_path == object_path:
1110
 
                    c.disable()
1111
 
                    clients.remove(c)
1112
 
                    return
1113
 
            raise KeyError
1114
 
        
1115
 
        del _interface
1116
 
    
1117
 
    mandos_server = MandosServer()
1118
 
    
1119
883
    for client in clients:
1120
 
        # Emit D-Bus signal
1121
 
        mandos_server.ClientAdded(client.dbus_object_path,
1122
 
                                  client.GetAllProperties())
1123
 
        client.enable()
 
884
        client.start()
1124
885
    
1125
886
    tcp_server.enable()
1126
887
    tcp_server.server_activate()
1144
905
        
1145
906
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
1146
907
                             lambda *args, **kwargs:
1147
 
                             (tcp_server.handle_request
1148
 
                              (*args[2:], **kwargs) or True))
 
908
                             tcp_server.handle_request\
 
909
                             (*args[2:], **kwargs) or True)
1149
910
        
1150
911
        logger.debug(u"Starting main loop")
1151
912
        main_loop.run()