/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-09-03 05:04:40 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080903050440-7cwzxestx6pvdy1i
* Makefile (mandos.8): Add dependency on "overview.xml" and
                       "legalnotice.xml".
  (mandos-keygen.8): New target.
  (mandos-conf.5): Added dependency on "legalnotice.xml".
  (plugin-runner.8mandos): New target
  (plugins.d/password-request.8mandos): - '' -

* mandos-options.xml (priority): Make wording server/client neutral.

* plugins.d/password-request.c (main): Changed .arg fields of the argp
                                       options struct to be more
                                       consistent with the manual.

* plugins.d/password-request.xml (OVERVIEW): Moved to after "OPTIONS".
  (OPTIONS): Improved wording and names of replaceables.

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
55
55
import stat
56
56
import logging
57
57
import logging.handlers
58
 
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
 
import ctypes.util
68
64
 
69
 
version = "1.0.2"
 
65
version = "1.0"
70
66
 
71
67
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'))
 
68
syslogger = logging.handlers.SysLogHandler\
 
69
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
70
             address = "/dev/log")
 
71
syslogger.setFormatter(logging.Formatter\
 
72
                        ('Mandos: %(levelname)s: %(message)s'))
77
73
logger.addHandler(syslogger)
78
74
 
79
75
console = logging.StreamHandler()
84
80
class AvahiError(Exception):
85
81
    def __init__(self, value):
86
82
        self.value = value
87
 
        super(AvahiError, self).__init__()
88
83
    def __str__(self):
89
84
        return repr(self.value)
90
85
 
112
107
                  a sensible number of times
113
108
    """
114
109
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
 
                 servicetype = None, port = None, TXT = None,
116
 
                 domain = "", host = "", max_renames = 32768):
 
110
                 type = None, port = None, TXT = None, domain = "",
 
111
                 host = "", max_renames = 32768):
117
112
        self.interface = interface
118
113
        self.name = name
119
 
        self.type = servicetype
 
114
        self.type = type
120
115
        self.port = port
121
 
        self.TXT = TXT if TXT is not None else []
 
116
        if TXT is None:
 
117
            self.TXT = []
 
118
        else:
 
119
            self.TXT = TXT
122
120
        self.domain = domain
123
121
        self.host = host
124
122
        self.rename_count = 0
128
126
        if self.rename_count >= self.max_renames:
129
127
            logger.critical(u"No suitable Zeroconf service name found"
130
128
                            u" after %i retries, exiting.",
131
 
                            self.rename_count)
 
129
                            rename_count)
132
130
            raise AvahiServiceError("Too many renames")
133
131
        self.name = server.GetAlternativeServiceName(self.name)
134
132
        logger.info(u"Changing Zeroconf service name to %r ...",
135
133
                    str(self.name))
136
 
        syslogger.setFormatter(logging.Formatter
 
134
        syslogger.setFormatter(logging.Formatter\
137
135
                               ('Mandos (%s): %%(levelname)s:'
138
 
                                ' %%(message)s' % self.name))
 
136
                               ' %%(message)s' % self.name))
139
137
        self.remove()
140
138
        self.add()
141
139
        self.rename_count += 1
147
145
        """Derived from the Avahi example code"""
148
146
        global group
149
147
        if group is None:
150
 
            group = dbus.Interface(bus.get_object
151
 
                                   (avahi.DBUS_NAME,
 
148
            group = dbus.Interface\
 
149
                    (bus.get_object(avahi.DBUS_NAME,
152
150
                                    server.EntryGroupNew()),
153
 
                                   avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
151
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
154
152
            group.connect_to_signal('StateChanged',
155
153
                                    entry_group_state_changed)
156
154
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
170
168
# End of Avahi example code
171
169
 
172
170
 
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):
 
171
class Client(object):
189
172
    """A representation of a client host served by this server.
190
173
    Attributes:
191
 
    name:       string; from the config file, used in log messages
 
174
    name:      string; from the config file, used in log messages
192
175
    fingerprint: string (40 or 32 hexadecimal digits); used to
193
176
                 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.
 
177
    secret:    bytestring; sent verbatim (over TLS) to client
 
178
    host:      string; available for use by the checker command
 
179
    created:   datetime.datetime(); object creation, not client host
 
180
    last_checked_ok: datetime.datetime() or None if not yet checked OK
 
181
    timeout:   datetime.timedelta(); How long from last_checked_ok
 
182
                                     until this client is invalid
 
183
    interval:  datetime.timedelta(); How often to start a new checker
 
184
    stop_hook: If set, called by stop() as stop_hook(self)
 
185
    checker:   subprocess.Popen(); a running checker process used
 
186
                                   to see if the client lives.
 
187
                                   'None' if no process is running.
207
188
    checker_initiator_tag: a gobject event source tag, or None
208
189
    stop_initiator_tag:    - '' -
209
190
    checker_callback_tag:  - '' -
211
192
                     client lives.  %() expansions are done at
212
193
                     runtime with vars(self) as dict, so that for
213
194
                     instance %(name)s can be used in the command.
214
 
    dbus_object_path: dbus.ObjectPath
215
195
    Private attibutes:
216
196
    _timeout: Real variable for 'timeout'
217
197
    _interval: Real variable for 'interval'
219
199
    _interval_milliseconds: - '' -
220
200
    """
221
201
    def _set_timeout(self, timeout):
222
 
        "Setter function for the 'timeout' attribute"
 
202
        "Setter function for 'timeout' attribute"
223
203
        self._timeout = timeout
224
204
        self._timeout_milliseconds = ((self.timeout.days
225
205
                                       * 24 * 60 * 60 * 1000)
226
206
                                      + (self.timeout.seconds * 1000)
227
207
                                      + (self.timeout.microseconds
228
208
                                         // 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)
 
209
    timeout = property(lambda self: self._timeout,
 
210
                       _set_timeout)
234
211
    del _set_timeout
235
 
    
236
212
    def _set_interval(self, interval):
237
 
        "Setter function for the 'interval' attribute"
 
213
        "Setter function for 'interval' attribute"
238
214
        self._interval = interval
239
215
        self._interval_milliseconds = ((self.interval.days
240
216
                                        * 24 * 60 * 60 * 1000)
242
218
                                          * 1000)
243
219
                                       + (self.interval.microseconds
244
220
                                          // 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)
 
221
    interval = property(lambda self: self._interval,
 
222
                        _set_interval)
250
223
    del _set_interval
251
 
    
252
 
    def __init__(self, name = None, stop_hook=None, config=None):
 
224
    def __init__(self, name = None, stop_hook=None, config={}):
253
225
        """Note: the 'checker' key in 'config' sets the
254
226
        'checker_command' attribute and *not* the 'checker'
255
227
        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
228
        self.name = name
264
229
        logger.debug(u"Creating client %r", self.name)
265
230
        # Uppercase and remove spaces from fingerprint for later
266
231
        # comparison purposes with return value from the fingerprint()
267
232
        # function
268
 
        self.fingerprint = (config["fingerprint"].upper()
269
 
                            .replace(u" ", u""))
 
233
        self.fingerprint = config["fingerprint"].upper()\
 
234
                           .replace(u" ", u"")
270
235
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
271
236
        if "secret" in config:
272
237
            self.secret = config["secret"].decode(u"base64")
273
238
        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()
 
239
            sf = open(config["secfile"])
 
240
            self.secret = sf.read()
 
241
            sf.close()
278
242
        else:
279
243
            raise TypeError(u"No secret or secfile for client %s"
280
244
                            % self.name)
281
245
        self.host = config.get("host", "")
282
 
        self.created = datetime.datetime.utcnow()
283
 
        self.started = False
284
 
        self.last_started = None
 
246
        self.created = datetime.datetime.now()
285
247
        self.last_checked_ok = None
286
248
        self.timeout = string_to_delta(config["timeout"])
287
249
        self.interval = string_to_delta(config["interval"])
290
252
        self.checker_initiator_tag = None
291
253
        self.stop_initiator_tag = None
292
254
        self.checker_callback_tag = None
293
 
        self.checker_command = config["checker"]
294
 
    
 
255
        self.check_command = config["checker"]
295
256
    def start(self):
296
257
        """Start this client's checker and timeout hooks"""
297
 
        self.last_started = datetime.datetime.utcnow()
298
258
        # Schedule a new checker to be started an 'interval' from now,
299
259
        # and every interval from then on.
300
 
        self.checker_initiator_tag = (gobject.timeout_add
301
 
                                      (self._interval_milliseconds,
302
 
                                       self.start_checker))
 
260
        self.checker_initiator_tag = gobject.timeout_add\
 
261
                                     (self._interval_milliseconds,
 
262
                                      self.start_checker)
303
263
        # Also start a new checker *right now*.
304
264
        self.start_checker()
305
265
        # 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
 
    
 
266
        self.stop_initiator_tag = gobject.timeout_add\
 
267
                                  (self._timeout_milliseconds,
 
268
                                   self.stop)
317
269
    def stop(self):
318
 
        """Stop this client."""
319
 
        if not getattr(self, "started", False):
 
270
        """Stop this client.
 
271
        The possibility that a client might be restarted is left open,
 
272
        but not currently used."""
 
273
        # If this client doesn't have a secret, it is already stopped.
 
274
        if hasattr(self, "secret") and self.secret:
 
275
            logger.info(u"Stopping client %s", self.name)
 
276
            self.secret = None
 
277
        else:
320
278
            return False
321
 
        logger.info(u"Stopping client %s", self.name)
322
279
        if getattr(self, "stop_initiator_tag", False):
323
280
            gobject.source_remove(self.stop_initiator_tag)
324
281
            self.stop_initiator_tag = None
328
285
        self.stop_checker()
329
286
        if self.stop_hook:
330
287
            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
288
        # Do not run this again if called by a gobject.timeout_add
336
289
        return False
337
 
    
338
290
    def __del__(self):
339
291
        self.stop_hook = None
340
292
        self.stop()
341
 
    
342
 
    def checker_callback(self, pid, condition, command):
 
293
    def checker_callback(self, pid, condition):
343
294
        """The checker has completed, so take appropriate actions."""
 
295
        now = datetime.datetime.now()
344
296
        self.checker_callback_tag = None
345
297
        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)):
 
298
        if os.WIFEXITED(condition) \
 
299
               and (os.WEXITSTATUS(condition) == 0):
351
300
            logger.info(u"Checker for %(name)s succeeded",
352
301
                        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()
 
302
            self.last_checked_ok = now
 
303
            gobject.source_remove(self.stop_initiator_tag)
 
304
            self.stop_initiator_tag = gobject.timeout_add\
 
305
                                      (self._timeout_milliseconds,
 
306
                                       self.stop)
358
307
        elif not os.WIFEXITED(condition):
359
308
            logger.warning(u"Checker for %(name)s crashed?",
360
309
                           vars(self))
361
 
            # Emit D-Bus signal
362
 
            self.CheckerCompleted(dbus.Boolean(False),
363
 
                                  dbus.UInt16(condition),
364
 
                                  dbus.String(command))
365
310
        else:
366
311
            logger.info(u"Checker for %(name)s failed",
367
312
                        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
313
    def start_checker(self):
389
314
        """Start a new checker subprocess if one is not running.
390
315
        If a checker already exists, leave it running and do
399
324
        # is as it should be.
400
325
        if self.checker is None:
401
326
            try:
402
 
                # In case checker_command has exactly one % operator
403
 
                command = self.checker_command % self.host
 
327
                # In case check_command has exactly one % operator
 
328
                command = self.check_command % self.host
404
329
            except TypeError:
405
330
                # Escape attributes for the shell
406
331
                escaped_attrs = dict((key, re.escape(str(val)))
407
332
                                     for key, val in
408
333
                                     vars(self).iteritems())
409
334
                try:
410
 
                    command = self.checker_command % escaped_attrs
 
335
                    command = self.check_command % escaped_attrs
411
336
                except TypeError, error:
412
337
                    logger.error(u'Could not format string "%s":'
413
 
                                 u' %s', self.checker_command, error)
 
338
                                 u' %s', self.check_command, error)
414
339
                    return True # Try again later
415
340
            try:
416
341
                logger.info(u"Starting checker %r for %s",
422
347
                self.checker = subprocess.Popen(command,
423
348
                                                close_fds=True,
424
349
                                                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))
 
350
                self.checker_callback_tag = gobject.child_watch_add\
 
351
                                            (self.checker.pid,
 
352
                                             self.checker_callback)
433
353
            except OSError, error:
434
354
                logger.error(u"Failed to start subprocess: %s",
435
355
                             error)
436
356
        # Re-run this periodically if run by gobject.timeout_add
437
357
        return True
438
 
    
439
358
    def stop_checker(self):
440
359
        """Force the checker process, if any, to stop."""
441
360
        if self.checker_callback_tag:
453
372
            if error.errno != errno.ESRCH: # No such process
454
373
                raise
455
374
        self.checker = None
456
 
        self.PropertyChanged(dbus.String(u"checker_running"),
457
 
                             dbus.Boolean(False, variant_level=1))
458
 
    
459
375
    def still_valid(self):
460
376
        """Has the timeout not yet passed for this client?"""
461
 
        if not getattr(self, "started", False):
462
 
            return False
463
 
        now = datetime.datetime.utcnow()
 
377
        now = datetime.datetime.now()
464
378
        if self.last_checked_ok is None:
465
379
            return now < (self.created + self.timeout)
466
380
        else:
467
381
            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
382
 
590
383
 
591
384
def peer_certificate(session):
592
385
    "Return the peer's OpenPGP certificate as a bytestring"
593
386
    # 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):
 
387
    if gnutls.library.functions.gnutls_certificate_type_get\
 
388
            (session._c_object) \
 
389
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
597
390
        # ...do the normal thing
598
391
        return session.peer_certificate
599
392
    list_size = ctypes.c_uint()
600
 
    cert_list = (gnutls.library.functions
601
 
                 .gnutls_certificate_get_peers
602
 
                 (session._c_object, ctypes.byref(list_size)))
 
393
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
 
394
        (session._c_object, ctypes.byref(list_size))
603
395
    if list_size.value == 0:
604
396
        return None
605
397
    cert = cert_list[0]
609
401
def fingerprint(openpgp):
610
402
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
611
403
    # 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))))
 
404
    datum = gnutls.library.types.gnutls_datum_t\
 
405
        (ctypes.cast(ctypes.c_char_p(openpgp),
 
406
                     ctypes.POINTER(ctypes.c_ubyte)),
 
407
         ctypes.c_uint(len(openpgp)))
617
408
    # New empty GnuTLS certificate
618
409
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
619
 
    (gnutls.library.functions
620
 
     .gnutls_openpgp_crt_init(ctypes.byref(crt)))
 
410
    gnutls.library.functions.gnutls_openpgp_crt_init\
 
411
        (ctypes.byref(crt))
621
412
    # 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))
 
413
    gnutls.library.functions.gnutls_openpgp_crt_import\
 
414
                    (crt, ctypes.byref(datum),
 
415
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
626
416
    # 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)))
 
417
    crtverify = ctypes.c_uint();
 
418
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
 
419
        (crt, 0, ctypes.byref(crtverify))
630
420
    if crtverify.value != 0:
631
421
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
632
422
        raise gnutls.errors.CertificateSecurityError("Verify failed")
633
423
    # New buffer for the fingerprint
634
 
    buf = ctypes.create_string_buffer(20)
635
 
    buf_len = ctypes.c_size_t()
 
424
    buffer = ctypes.create_string_buffer(20)
 
425
    buffer_length = ctypes.c_size_t()
636
426
    # 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)))
 
427
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
 
428
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
640
429
    # Deinit the certificate
641
430
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
642
431
    # Convert the buffer to a Python bytestring
643
 
    fpr = ctypes.string_at(buf, buf_len.value)
 
432
    fpr = ctypes.string_at(buffer, buffer_length.value)
644
433
    # Convert the bytestring to hexadecimal notation
645
434
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
646
435
    return hex_fpr
647
436
 
648
437
 
649
 
class TCP_handler(SocketServer.BaseRequestHandler, object):
 
438
class tcp_handler(SocketServer.BaseRequestHandler, object):
650
439
    """A TCP request handler class.
651
440
    Instantiated by IPv6_TCPServer for each request to handle it.
652
441
    Note: This will run in its own forked process."""
653
442
    
654
443
    def handle(self):
655
444
        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()))
 
445
                     unicode(self.client_address))
 
446
        session = gnutls.connection.ClientSession\
 
447
                  (self.request, gnutls.connection.X509Credentials())
661
448
        
662
449
        line = self.request.makefile().readline()
663
450
        logger.debug(u"Protocol version: %r", line)
676
463
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
677
464
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
678
465
        #                "+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))
 
466
        priority = "NORMAL"             # Fallback default, since this
 
467
                                        # MUST be set.
 
468
        if self.server.settings["priority"]:
 
469
            priority = self.server.settings["priority"]
 
470
        gnutls.library.functions.gnutls_priority_set_direct\
 
471
            (session._c_object, priority, None);
684
472
        
685
473
        try:
686
474
            session.handshake()
696
484
            session.bye()
697
485
            return
698
486
        logger.debug(u"Fingerprint: %s", fpr)
 
487
        client = None
699
488
        for c in self.server.clients:
700
489
            if c.fingerprint == fpr:
701
490
                client = c
702
491
                break
703
 
        else:
 
492
        if not client:
704
493
            logger.warning(u"Client not found for fingerprint: %s",
705
494
                           fpr)
706
495
            session.bye()
713
502
                           vars(client))
714
503
            session.bye()
715
504
            return
716
 
        ## This won't work here, since we're in a fork.
717
 
        # client.bump_timeout()
718
505
        sent_size = 0
719
506
        while sent_size < len(client.secret):
720
507
            sent = session.send(client.secret[sent_size:])
725
512
        session.bye()
726
513
 
727
514
 
728
 
class IPv6_TCPServer(SocketServer.ForkingMixIn,
729
 
                     SocketServer.TCPServer, object):
 
515
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
730
516
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
731
517
    Attributes:
732
518
        settings:       Server settings
733
519
        clients:        Set() of Client objects
734
 
        enabled:        Boolean; whether this server is activated yet
735
520
    """
736
521
    address_family = socket.AF_INET6
737
522
    def __init__(self, *args, **kwargs):
741
526
        if "clients" in kwargs:
742
527
            self.clients = kwargs["clients"]
743
528
            del kwargs["clients"]
744
 
        self.enabled = False
745
 
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
 
529
        return super(type(self), self).__init__(*args, **kwargs)
746
530
    def server_bind(self):
747
531
        """This overrides the normal server_bind() function
748
532
        to bind to an interface if one was specified, and also NOT to
777
561
#                                            if_nametoindex
778
562
#                                            (self.settings
779
563
#                                             ["interface"]))
780
 
            return super(IPv6_TCPServer, self).server_bind()
781
 
    def server_activate(self):
782
 
        if self.enabled:
783
 
            return super(IPv6_TCPServer, self).server_activate()
784
 
    def enable(self):
785
 
        self.enabled = True
 
564
            return super(type(self), self).server_bind()
786
565
 
787
566
 
788
567
def string_to_delta(interval):
804
583
    timevalue = datetime.timedelta(0)
805
584
    for s in interval.split():
806
585
        try:
807
 
            suffix = unicode(s[-1])
808
 
            value = int(s[:-1])
 
586
            suffix=unicode(s[-1])
 
587
            value=int(s[:-1])
809
588
            if suffix == u"d":
810
589
                delta = datetime.timedelta(value)
811
590
            elif suffix == u"s":
851
630
    """Call the C function if_nametoindex(), or equivalent"""
852
631
    global if_nametoindex
853
632
    try:
854
 
        if_nametoindex = (ctypes.cdll.LoadLibrary
855
 
                          (ctypes.util.find_library("c"))
856
 
                          .if_nametoindex)
 
633
        if "ctypes.util" not in sys.modules:
 
634
            import ctypes.util
 
635
        if_nametoindex = ctypes.cdll.LoadLibrary\
 
636
            (ctypes.util.find_library("c")).if_nametoindex
857
637
    except (OSError, AttributeError):
858
638
        if "struct" not in sys.modules:
859
639
            import struct
862
642
        def if_nametoindex(interface):
863
643
            "Get an interface index the hard way, i.e. using fcntl()"
864
644
            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))
 
645
            s = socket.socket()
 
646
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
647
                                struct.pack("16s16x", interface))
 
648
            s.close()
868
649
            interface_index = struct.unpack("I", ifreq[16:20])[0]
869
650
            return interface_index
870
651
    return if_nametoindex(interface)
894
675
 
895
676
 
896
677
def main():
 
678
    global main_loop_started
 
679
    main_loop_started = False
 
680
    
897
681
    parser = OptionParser(version = "%%prog %s" % version)
898
682
    parser.add_option("-i", "--interface", type="string",
899
683
                      metavar="IF", help="Bind to interface IF")
914
698
                      default="/etc/mandos", metavar="DIR",
915
699
                      help="Directory to search for configuration"
916
700
                      " files")
917
 
    options = parser.parse_args()[0]
 
701
    (options, args) = parser.parse_args()
918
702
    
919
703
    if options.check:
920
704
        import doctest
938
722
    # Convert the SafeConfigParser object to a dict
939
723
    server_settings = server_config.defaults()
940
724
    # Use getboolean on the boolean config option
941
 
    server_settings["debug"] = (server_config.getboolean
942
 
                                ("DEFAULT", "debug"))
 
725
    server_settings["debug"] = server_config.getboolean\
 
726
                               ("DEFAULT", "debug")
943
727
    del server_config
944
728
    
945
729
    # Override the settings from the config file with command line
959
743
        console.setLevel(logging.WARNING)
960
744
    
961
745
    if server_settings["servicename"] != "Mandos":
962
 
        syslogger.setFormatter(logging.Formatter
 
746
        syslogger.setFormatter(logging.Formatter\
963
747
                               ('Mandos (%s): %%(levelname)s:'
964
748
                                ' %%(message)s'
965
749
                                % server_settings["servicename"]))
974
758
    client_config.read(os.path.join(server_settings["configdir"],
975
759
                                    "clients.conf"))
976
760
    
977
 
    clients = Set()
978
 
    tcp_server = IPv6_TCPServer((server_settings["address"],
979
 
                                 server_settings["port"]),
980
 
                                TCP_handler,
981
 
                                settings=server_settings,
982
 
                                clients=clients)
983
 
    pidfilename = "/var/run/mandos.pid"
984
 
    try:
985
 
        pidfile = open(pidfilename, "w")
986
 
    except IOError, error:
987
 
        logger.error("Could not open file %r", pidfilename)
988
 
    
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
1009
 
    try:
1010
 
        os.setuid(uid)
1011
 
        os.setgid(gid)
1012
 
    except OSError, error:
1013
 
        if error[0] != errno.EPERM:
1014
 
            raise error
1015
 
    
1016
761
    global service
1017
762
    service = AvahiService(name = server_settings["servicename"],
1018
 
                           servicetype = "_mandos._tcp", )
 
763
                           type = "_mandos._tcp", );
1019
764
    if server_settings["interface"]:
1020
 
        service.interface = (if_nametoindex
1021
 
                             (server_settings["interface"]))
 
765
        service.interface = if_nametoindex\
 
766
                            (server_settings["interface"])
1022
767
    
1023
768
    global main_loop
1024
769
    global bus
1031
776
                                           avahi.DBUS_PATH_SERVER),
1032
777
                            avahi.DBUS_INTERFACE_SERVER)
1033
778
    # End of Avahi example code
1034
 
    bus_name = dbus.service.BusName(u"org.mandos-system.Mandos", bus)
 
779
    
 
780
    clients = Set()
 
781
    def remove_from_clients(client):
 
782
        clients.remove(client)
 
783
        if not clients:
 
784
            logger.critical(u"No clients left, exiting")
 
785
            sys.exit()
1035
786
    
1036
787
    clients.update(Set(Client(name = section,
 
788
                              stop_hook = remove_from_clients,
1037
789
                              config
1038
790
                              = dict(client_config.items(section)))
1039
791
                       for section in client_config.sections()))
1053
805
        # Close all input and output, do double fork, etc.
1054
806
        daemon()
1055
807
    
 
808
    pidfilename = "/var/run/mandos/mandos.pid"
 
809
    pid = os.getpid()
1056
810
    try:
1057
 
        pid = os.getpid()
 
811
        pidfile = open(pidfilename, "w")
1058
812
        pidfile.write(str(pid) + "\n")
1059
813
        pidfile.close()
1060
814
        del pidfile
1061
 
    except IOError:
1062
 
        logger.error(u"Could not write to file %r with PID %d",
1063
 
                     pidfilename, pid)
1064
 
    except NameError:
1065
 
        # "pidfile" was never created
1066
 
        pass
1067
 
    del pidfilename
 
815
    except IOError, err:
 
816
        logger.error(u"Could not write %s file with PID %d",
 
817
                     pidfilename, os.getpid())
1068
818
    
1069
819
    def cleanup():
1070
820
        "Cleanup function; run on exit"
1087
837
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1088
838
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1089
839
    
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
840
    for client in clients:
1132
 
        # Emit D-Bus signal
1133
 
        mandos_server.ClientAdded(client.dbus_object_path,
1134
 
                                  client.GetAllProperties())
1135
841
        client.start()
1136
842
    
1137
 
    tcp_server.enable()
1138
 
    tcp_server.server_activate()
1139
 
    
 
843
    tcp_server = IPv6_TCPServer((server_settings["address"],
 
844
                                 server_settings["port"]),
 
845
                                tcp_handler,
 
846
                                settings=server_settings,
 
847
                                clients=clients)
1140
848
    # Find out what port we got
1141
849
    service.port = tcp_server.socket.getsockname()[1]
1142
850
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
1156
864
        
1157
865
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
1158
866
                             lambda *args, **kwargs:
1159
 
                             (tcp_server.handle_request
1160
 
                              (*args[2:], **kwargs) or True))
 
867
                             tcp_server.handle_request\
 
868
                             (*args[2:], **kwargs) or True)
1161
869
        
1162
870
        logger.debug(u"Starting main loop")
 
871
        main_loop_started = True
1163
872
        main_loop.run()
1164
873
    except AvahiError, error:
1165
874
        logger.critical(u"AvahiError: %s" + unicode(error))