/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: 2011-03-08 19:09:03 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110308190903-j499ebtb9bpk31ar
* INSTALL: Updated.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
# along with this program.  If not, see
29
29
# <http://www.gnu.org/licenses/>.
30
30
31
 
# Contact the authors at <mandos@recompile.se>.
 
31
# Contact the authors at <mandos@fukt.bsnet.se>.
32
32
33
33
 
34
34
from __future__ import (division, absolute_import, print_function,
36
36
 
37
37
import SocketServer as socketserver
38
38
import socket
39
 
import argparse
 
39
import optparse
40
40
import datetime
41
41
import errno
42
42
import gnutls.crypto
62
62
import functools
63
63
import cPickle as pickle
64
64
import multiprocessing
65
 
import types
66
 
import binascii
67
 
import tempfile
68
65
 
69
66
import dbus
70
67
import dbus.service
75
72
import ctypes.util
76
73
import xml.dom.minidom
77
74
import inspect
78
 
import GnuPGInterface
79
75
 
80
76
try:
81
77
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
85
81
    except ImportError:
86
82
        SO_BINDTODEVICE = None
87
83
 
88
 
version = "1.4.1"
89
 
stored_state_file = "clients.pickle"
90
 
 
91
 
logger = logging.getLogger()
 
84
 
 
85
version = "1.2.3"
 
86
 
 
87
#logger = logging.getLogger('mandos')
 
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
              address = str("/dev/log")))
95
 
 
96
 
try:
97
 
    if_nametoindex = (ctypes.cdll.LoadLibrary
98
 
                      (ctypes.util.find_library("c"))
99
 
                      .if_nametoindex)
100
 
except (OSError, AttributeError):
101
 
    def if_nametoindex(interface):
102
 
        "Get an interface index the hard way, i.e. using fcntl()"
103
 
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
104
 
        with contextlib.closing(socket.socket()) as s:
105
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
106
 
                                struct.pack(str("16s16x"),
107
 
                                            interface))
108
 
        interface_index = struct.unpack(str("I"),
109
 
                                        ifreq[16:20])[0]
110
 
        return interface_index
111
 
 
112
 
 
113
 
def initlogger(level=logging.WARNING):
114
 
    """init logger and add loglevel"""
115
 
    
116
 
    syslogger.setFormatter(logging.Formatter
117
 
                           ('Mandos [%(process)d]: %(levelname)s:'
118
 
                            ' %(message)s'))
119
 
    logger.addHandler(syslogger)
120
 
    
121
 
    console = logging.StreamHandler()
122
 
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
123
 
                                           ' [%(process)d]:'
124
 
                                           ' %(levelname)s:'
125
 
                                           ' %(message)s'))
126
 
    logger.addHandler(console)
127
 
    logger.setLevel(level)
128
 
 
129
 
 
130
 
class PGPError(Exception):
131
 
    """Exception if encryption/decryption fails"""
132
 
    pass
133
 
 
134
 
 
135
 
class PGPEngine(object):
136
 
    """A simple class for OpenPGP symmetric encryption & decryption"""
137
 
    def __init__(self):
138
 
        self.gnupg = GnuPGInterface.GnuPG()
139
 
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
 
        self.gnupg = GnuPGInterface.GnuPG()
141
 
        self.gnupg.options.meta_interactive = False
142
 
        self.gnupg.options.homedir = self.tempdir
143
 
        self.gnupg.options.extra_args.extend(['--force-mdc',
144
 
                                              '--quiet'])
145
 
    
146
 
    def __enter__(self):
147
 
        return self
148
 
    
149
 
    def __exit__ (self, exc_type, exc_value, traceback):
150
 
        self._cleanup()
151
 
        return False
152
 
    
153
 
    def __del__(self):
154
 
        self._cleanup()
155
 
    
156
 
    def _cleanup(self):
157
 
        if self.tempdir is not None:
158
 
            # Delete contents of tempdir
159
 
            for root, dirs, files in os.walk(self.tempdir,
160
 
                                             topdown = False):
161
 
                for filename in files:
162
 
                    os.remove(os.path.join(root, filename))
163
 
                for dirname in dirs:
164
 
                    os.rmdir(os.path.join(root, dirname))
165
 
            # Remove tempdir
166
 
            os.rmdir(self.tempdir)
167
 
            self.tempdir = None
168
 
    
169
 
    def password_encode(self, password):
170
 
        # Passphrase can not be empty and can not contain newlines or
171
 
        # NUL bytes.  So we prefix it and hex encode it.
172
 
        return b"mandos" + binascii.hexlify(password)
173
 
    
174
 
    def encrypt(self, data, password):
175
 
        self.gnupg.passphrase = self.password_encode(password)
176
 
        with open(os.devnull) as devnull:
177
 
            try:
178
 
                proc = self.gnupg.run(['--symmetric'],
179
 
                                      create_fhs=['stdin', 'stdout'],
180
 
                                      attach_fhs={'stderr': devnull})
181
 
                with contextlib.closing(proc.handles['stdin']) as f:
182
 
                    f.write(data)
183
 
                with contextlib.closing(proc.handles['stdout']) as f:
184
 
                    ciphertext = f.read()
185
 
                proc.wait()
186
 
            except IOError as e:
187
 
                raise PGPError(e)
188
 
        self.gnupg.passphrase = None
189
 
        return ciphertext
190
 
    
191
 
    def decrypt(self, data, password):
192
 
        self.gnupg.passphrase = self.password_encode(password)
193
 
        with open(os.devnull) as devnull:
194
 
            try:
195
 
                proc = self.gnupg.run(['--decrypt'],
196
 
                                      create_fhs=['stdin', 'stdout'],
197
 
                                      attach_fhs={'stderr': devnull})
198
 
                with contextlib.closing(proc.handles['stdin'] ) as f:
199
 
                    f.write(data)
200
 
                with contextlib.closing(proc.handles['stdout']) as f:
201
 
                    decrypted_plaintext = f.read()
202
 
                proc.wait()
203
 
            except IOError as e:
204
 
                raise PGPError(e)
205
 
        self.gnupg.passphrase = None
206
 
        return decrypted_plaintext
207
 
 
208
 
 
 
92
syslogger.setFormatter(logging.Formatter
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
94
                        ' %(message)s'))
 
95
logger.addHandler(syslogger)
 
96
 
 
97
console = logging.StreamHandler()
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
99
                                       ' %(levelname)s:'
 
100
                                       ' %(message)s'))
 
101
logger.addHandler(console)
209
102
 
210
103
class AvahiError(Exception):
211
104
    def __init__(self, value, *args, **kwargs):
258
151
        self.group = None       # our entry group
259
152
        self.server = None
260
153
        self.bus = bus
261
 
        self.entry_group_state_changed_match = None
262
154
    def rename(self):
263
155
        """Derived from the Avahi example code"""
264
156
        if self.rename_count >= self.max_renames:
266
158
                            " after %i retries, exiting.",
267
159
                            self.rename_count)
268
160
            raise AvahiServiceError("Too many renames")
269
 
        self.name = unicode(self.server
270
 
                            .GetAlternativeServiceName(self.name))
 
161
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
271
162
        logger.info("Changing Zeroconf service name to %r ...",
272
163
                    self.name)
 
164
        syslogger.setFormatter(logging.Formatter
 
165
                               ('Mandos (%s) [%%(process)d]:'
 
166
                                ' %%(levelname)s: %%(message)s'
 
167
                                % self.name))
273
168
        self.remove()
274
169
        try:
275
170
            self.add()
276
 
        except dbus.exceptions.DBusException as error:
 
171
        except dbus.exceptions.DBusException, error:
277
172
            logger.critical("DBusException: %s", error)
278
173
            self.cleanup()
279
174
            os._exit(1)
280
175
        self.rename_count += 1
281
176
    def remove(self):
282
177
        """Derived from the Avahi example code"""
283
 
        if self.entry_group_state_changed_match is not None:
284
 
            self.entry_group_state_changed_match.remove()
285
 
            self.entry_group_state_changed_match = None
286
178
        if self.group is not None:
287
179
            self.group.Reset()
288
180
    def add(self):
289
181
        """Derived from the Avahi example code"""
290
 
        self.remove()
291
182
        if self.group is None:
292
183
            self.group = dbus.Interface(
293
184
                self.bus.get_object(avahi.DBUS_NAME,
294
185
                                    self.server.EntryGroupNew()),
295
186
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
296
 
        self.entry_group_state_changed_match = (
297
 
            self.group.connect_to_signal(
298
 
                'StateChanged', self.entry_group_state_changed))
 
187
            self.group.connect_to_signal('StateChanged',
 
188
                                         self
 
189
                                         .entry_group_state_changed)
299
190
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
300
191
                     self.name, self.type)
301
192
        self.group.AddService(
324
215
    def cleanup(self):
325
216
        """Derived from the Avahi example code"""
326
217
        if self.group is not None:
327
 
            try:
328
 
                self.group.Free()
329
 
            except (dbus.exceptions.UnknownMethodException,
330
 
                    dbus.exceptions.DBusException):
331
 
                pass
 
218
            self.group.Free()
332
219
            self.group = None
333
 
        self.remove()
334
 
    def server_state_changed(self, state, error=None):
 
220
    def server_state_changed(self, state):
335
221
        """Derived from the Avahi example code"""
336
222
        logger.debug("Avahi server state change: %i", state)
337
 
        bad_states = { avahi.SERVER_INVALID:
338
 
                           "Zeroconf server invalid",
339
 
                       avahi.SERVER_REGISTERING: None,
340
 
                       avahi.SERVER_COLLISION:
341
 
                           "Zeroconf server name collision",
342
 
                       avahi.SERVER_FAILURE:
343
 
                           "Zeroconf server failure" }
344
 
        if state in bad_states:
345
 
            if bad_states[state] is not None:
346
 
                if error is None:
347
 
                    logger.error(bad_states[state])
348
 
                else:
349
 
                    logger.error(bad_states[state] + ": %r", error)
350
 
            self.cleanup()
 
223
        if state == avahi.SERVER_COLLISION:
 
224
            logger.error("Zeroconf server name collision")
 
225
            self.remove()
351
226
        elif state == avahi.SERVER_RUNNING:
352
227
            self.add()
353
 
        else:
354
 
            if error is None:
355
 
                logger.debug("Unknown state: %r", state)
356
 
            else:
357
 
                logger.debug("Unknown state: %r: %r", state, error)
358
228
    def activate(self):
359
229
        """Derived from the Avahi example code"""
360
230
        if self.server is None:
361
231
            self.server = dbus.Interface(
362
232
                self.bus.get_object(avahi.DBUS_NAME,
363
 
                                    avahi.DBUS_PATH_SERVER,
364
 
                                    follow_name_owner_changes=True),
 
233
                                    avahi.DBUS_PATH_SERVER),
365
234
                avahi.DBUS_INTERFACE_SERVER)
366
235
        self.server.connect_to_signal("StateChanged",
367
236
                                 self.server_state_changed)
368
237
        self.server_state_changed(self.server.GetState())
369
238
 
370
 
class AvahiServiceToSyslog(AvahiService):
371
 
    def rename(self):
372
 
        """Add the new name to the syslog messages"""
373
 
        ret = AvahiService.rename(self)
374
 
        syslogger.setFormatter(logging.Formatter
375
 
                               ('Mandos (%s) [%%(process)d]:'
376
 
                                ' %%(levelname)s: %%(message)s'
377
 
                                % self.name))
378
 
        return ret
379
239
 
380
 
def timedelta_to_milliseconds(td):
381
 
    "Convert a datetime.timedelta() to milliseconds"
382
 
    return ((td.days * 24 * 60 * 60 * 1000)
383
 
            + (td.seconds * 1000)
384
 
            + (td.microseconds // 1000))
385
 
        
386
240
class Client(object):
387
241
    """A representation of a client host served by this server.
388
242
    
389
243
    Attributes:
390
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
244
    _approved:   bool(); 'None' if not yet approved/disapproved
391
245
    approval_delay: datetime.timedelta(); Time to wait for approval
392
246
    approval_duration: datetime.timedelta(); Duration of one approval
393
247
    checker:    subprocess.Popen(); a running checker process used
400
254
                     instance %(name)s can be used in the command.
401
255
    checker_initiator_tag: a gobject event source tag, or None
402
256
    created:    datetime.datetime(); (UTC) object creation
403
 
    client_structure: Object describing what attributes a client has
404
 
                      and is used for storing the client at exit
405
257
    current_checker_command: string; current running checker_command
 
258
    disable_hook:  If set, called by disable() as disable_hook(self)
406
259
    disable_initiator_tag: a gobject event source tag, or None
407
260
    enabled:    bool()
408
261
    fingerprint: string (40 or 32 hexadecimal digits); used to
411
264
    interval:   datetime.timedelta(); How often to start a new checker
412
265
    last_approval_request: datetime.datetime(); (UTC) or None
413
266
    last_checked_ok: datetime.datetime(); (UTC) or None
414
 
    last_checker_status: integer between 0 and 255 reflecting exit
415
 
                         status of last checker. -1 reflects crashed
416
 
                         checker, or None.
417
 
    last_enabled: datetime.datetime(); (UTC) or None
 
267
    last_enabled: datetime.datetime(); (UTC)
418
268
    name:       string; from the config file, used in log messages and
419
269
                        D-Bus identifiers
420
270
    secret:     bytestring; sent verbatim (over TLS) to client
421
271
    timeout:    datetime.timedelta(); How long from last_checked_ok
422
272
                                      until this client is disabled
423
 
    extended_timeout:   extra long timeout when password has been sent
424
273
    runtime_expansions: Allowed attributes for runtime expansion.
425
 
    expires:    datetime.datetime(); time (UTC) when a client will be
426
 
                disabled, or None
427
274
    """
428
275
    
429
276
    runtime_expansions = ("approval_delay", "approval_duration",
430
277
                          "created", "enabled", "fingerprint",
431
278
                          "host", "interval", "last_checked_ok",
432
279
                          "last_enabled", "name", "timeout")
433
 
    client_defaults = { "timeout": "5m",
434
 
                        "extended_timeout": "15m",
435
 
                        "interval": "2m",
436
 
                        "checker": "fping -q -- %%(host)s",
437
 
                        "host": "",
438
 
                        "approval_delay": "0s",
439
 
                        "approval_duration": "1s",
440
 
                        "approved_by_default": "True",
441
 
                        "enabled": "True",
442
 
                        }
 
280
    
 
281
    @staticmethod
 
282
    def _timedelta_to_milliseconds(td):
 
283
        "Convert a datetime.timedelta() to milliseconds"
 
284
        return ((td.days * 24 * 60 * 60 * 1000)
 
285
                + (td.seconds * 1000)
 
286
                + (td.microseconds // 1000))
443
287
    
444
288
    def timeout_milliseconds(self):
445
289
        "Return the 'timeout' attribute in milliseconds"
446
 
        return timedelta_to_milliseconds(self.timeout)
447
 
    
448
 
    def extended_timeout_milliseconds(self):
449
 
        "Return the 'extended_timeout' attribute in milliseconds"
450
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
290
        return self._timedelta_to_milliseconds(self.timeout)
451
291
    
452
292
    def interval_milliseconds(self):
453
293
        "Return the 'interval' attribute in milliseconds"
454
 
        return timedelta_to_milliseconds(self.interval)
455
 
    
 
294
        return self._timedelta_to_milliseconds(self.interval)
 
295
 
456
296
    def approval_delay_milliseconds(self):
457
 
        return timedelta_to_milliseconds(self.approval_delay)
458
 
 
459
 
    @staticmethod
460
 
    def config_parser(config):
461
 
        """ Construct a new dict of client settings of this form:
462
 
        { client_name: {setting_name: value, ...}, ...}
463
 
        with exceptions for any special settings as defined above"""
464
 
        settings = {}
465
 
        for client_name in config.sections():
466
 
            section = dict(config.items(client_name))
467
 
            client = settings[client_name] = {}
468
 
            
469
 
            client["host"] = section["host"]
470
 
            # Reformat values from string types to Python types
471
 
            client["approved_by_default"] = config.getboolean(
472
 
                client_name, "approved_by_default")
473
 
            client["enabled"] = config.getboolean(client_name, "enabled")
474
 
            
475
 
            client["fingerprint"] = (section["fingerprint"].upper()
476
 
                                     .replace(" ", ""))
477
 
            if "secret" in section:
478
 
                client["secret"] = section["secret"].decode("base64")
479
 
            elif "secfile" in section:
480
 
                with open(os.path.expanduser(os.path.expandvars
481
 
                                             (section["secfile"])),
482
 
                          "rb") as secfile:
483
 
                    client["secret"] = secfile.read()
484
 
            else:
485
 
                raise TypeError("No secret or secfile for section %s"
486
 
                                % section)
487
 
            client["timeout"] = string_to_delta(section["timeout"])
488
 
            client["extended_timeout"] = string_to_delta(
489
 
                section["extended_timeout"])
490
 
            client["interval"] = string_to_delta(section["interval"])
491
 
            client["approval_delay"] = string_to_delta(
492
 
                section["approval_delay"])
493
 
            client["approval_duration"] = string_to_delta(
494
 
                section["approval_duration"])
495
 
            client["checker_command"] = section["checker"]
496
 
            client["last_approval_request"] = None
497
 
            client["last_checked_ok"] = None
498
 
            client["last_checker_status"] = None
499
 
            if client["enabled"]:
500
 
                client["last_enabled"] = datetime.datetime.utcnow()
501
 
                client["expires"] = (datetime.datetime.utcnow()
502
 
                                     + client["timeout"])
503
 
            else:
504
 
                client["last_enabled"] = None
505
 
                client["expires"] = None
506
 
 
507
 
        return settings
508
 
        
509
 
        
510
 
    def __init__(self, settings, name = None):
 
297
        return self._timedelta_to_milliseconds(self.approval_delay)
 
298
    
 
299
    def __init__(self, name = None, disable_hook=None, config=None):
511
300
        """Note: the 'checker' key in 'config' sets the
512
301
        'checker_command' attribute and *not* the 'checker'
513
302
        attribute."""
514
303
        self.name = name
515
 
        # adding all client settings
516
 
        for setting, value in settings.iteritems():
517
 
            setattr(self, setting, value)
518
 
        
 
304
        if config is None:
 
305
            config = {}
519
306
        logger.debug("Creating client %r", self.name)
520
307
        # Uppercase and remove spaces from fingerprint for later
521
308
        # comparison purposes with return value from the fingerprint()
522
309
        # function
 
310
        self.fingerprint = (config["fingerprint"].upper()
 
311
                            .replace(" ", ""))
523
312
        logger.debug("  Fingerprint: %s", self.fingerprint)
524
 
        self.created = settings.get("created", datetime.datetime.utcnow())
525
 
 
526
 
        # attributes specific for this server instance
 
313
        if "secret" in config:
 
314
            self.secret = config["secret"].decode("base64")
 
315
        elif "secfile" in config:
 
316
            with open(os.path.expanduser(os.path.expandvars
 
317
                                         (config["secfile"])),
 
318
                      "rb") as secfile:
 
319
                self.secret = secfile.read()
 
320
        else:
 
321
            raise TypeError("No secret or secfile for client %s"
 
322
                            % self.name)
 
323
        self.host = config.get("host", "")
 
324
        self.created = datetime.datetime.utcnow()
 
325
        self.enabled = False
 
326
        self.last_approval_request = None
 
327
        self.last_enabled = None
 
328
        self.last_checked_ok = None
 
329
        self.timeout = string_to_delta(config["timeout"])
 
330
        self.interval = string_to_delta(config["interval"])
 
331
        self.disable_hook = disable_hook
527
332
        self.checker = None
528
333
        self.checker_initiator_tag = None
529
334
        self.disable_initiator_tag = None
530
335
        self.checker_callback_tag = None
 
336
        self.checker_command = config["checker"]
531
337
        self.current_checker_command = None
532
 
        self.approved = None
 
338
        self.last_connect = None
 
339
        self._approved = None
 
340
        self.approved_by_default = config.get("approved_by_default",
 
341
                                              True)
533
342
        self.approvals_pending = 0
534
 
        self.changedstate = (multiprocessing_manager
535
 
                             .Condition(multiprocessing_manager
536
 
                                        .Lock()))
537
 
        self.client_structure = [attr for attr in
538
 
                                 self.__dict__.iterkeys()
539
 
                                 if not attr.startswith("_")]
540
 
        self.client_structure.append("client_structure")
541
 
        
542
 
        for name, t in inspect.getmembers(type(self),
543
 
                                          lambda obj:
544
 
                                              isinstance(obj,
545
 
                                                         property)):
546
 
            if not name.startswith("_"):
547
 
                self.client_structure.append(name)
 
343
        self.approval_delay = string_to_delta(
 
344
            config["approval_delay"])
 
345
        self.approval_duration = string_to_delta(
 
346
            config["approval_duration"])
 
347
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
548
348
    
549
 
    # Send notice to process children that client state has changed
550
349
    def send_changedstate(self):
551
 
        with self.changedstate:
552
 
            self.changedstate.notify_all()
553
 
    
 
350
        self.changedstate.acquire()
 
351
        self.changedstate.notify_all()
 
352
        self.changedstate.release()
 
353
        
554
354
    def enable(self):
555
355
        """Start this client's checker and timeout hooks"""
556
356
        if getattr(self, "enabled", False):
557
357
            # Already enabled
558
358
            return
559
359
        self.send_changedstate()
560
 
        self.expires = datetime.datetime.utcnow() + self.timeout
561
 
        self.enabled = True
562
360
        self.last_enabled = datetime.datetime.utcnow()
563
 
        self.init_checker()
 
361
        # Schedule a new checker to be started an 'interval' from now,
 
362
        # and every interval from then on.
 
363
        self.checker_initiator_tag = (gobject.timeout_add
 
364
                                      (self.interval_milliseconds(),
 
365
                                       self.start_checker))
 
366
        # Schedule a disable() when 'timeout' has passed
 
367
        self.disable_initiator_tag = (gobject.timeout_add
 
368
                                   (self.timeout_milliseconds(),
 
369
                                    self.disable))
 
370
        self.enabled = True
 
371
        # Also start a new checker *right now*.
 
372
        self.start_checker()
564
373
    
565
374
    def disable(self, quiet=True):
566
375
        """Disable this client."""
573
382
        if getattr(self, "disable_initiator_tag", False):
574
383
            gobject.source_remove(self.disable_initiator_tag)
575
384
            self.disable_initiator_tag = None
576
 
        self.expires = None
577
385
        if getattr(self, "checker_initiator_tag", False):
578
386
            gobject.source_remove(self.checker_initiator_tag)
579
387
            self.checker_initiator_tag = None
580
388
        self.stop_checker()
 
389
        if self.disable_hook:
 
390
            self.disable_hook(self)
581
391
        self.enabled = False
582
392
        # Do not run this again if called by a gobject.timeout_add
583
393
        return False
584
394
    
585
395
    def __del__(self):
 
396
        self.disable_hook = None
586
397
        self.disable()
587
398
    
588
 
    def init_checker(self):
589
 
        # Schedule a new checker to be started an 'interval' from now,
590
 
        # and every interval from then on.
591
 
        self.checker_initiator_tag = (gobject.timeout_add
592
 
                                      (self.interval_milliseconds(),
593
 
                                       self.start_checker))
594
 
        # Schedule a disable() when 'timeout' has passed
595
 
        self.disable_initiator_tag = (gobject.timeout_add
596
 
                                   (self.timeout_milliseconds(),
597
 
                                    self.disable))
598
 
        # Also start a new checker *right now*.
599
 
        self.start_checker()
600
 
    
601
399
    def checker_callback(self, pid, condition, command):
602
400
        """The checker has completed, so take appropriate actions."""
603
401
        self.checker_callback_tag = None
604
402
        self.checker = None
605
403
        if os.WIFEXITED(condition):
606
 
            self.last_checker_status = os.WEXITSTATUS(condition)
607
 
            if self.last_checker_status == 0:
 
404
            exitstatus = os.WEXITSTATUS(condition)
 
405
            if exitstatus == 0:
608
406
                logger.info("Checker for %(name)s succeeded",
609
407
                            vars(self))
610
408
                self.checked_ok()
612
410
                logger.info("Checker for %(name)s failed",
613
411
                            vars(self))
614
412
        else:
615
 
            self.last_checker_status = -1
616
413
            logger.warning("Checker for %(name)s crashed?",
617
414
                           vars(self))
618
415
    
619
 
    def checked_ok(self, timeout=None):
 
416
    def checked_ok(self):
620
417
        """Bump up the timeout for this client.
621
418
        
622
419
        This should only be called when the client has been seen,
623
420
        alive and well.
624
421
        """
625
 
        if timeout is None:
626
 
            timeout = self.timeout
627
422
        self.last_checked_ok = datetime.datetime.utcnow()
628
 
        if self.disable_initiator_tag is not None:
629
 
            gobject.source_remove(self.disable_initiator_tag)
630
 
        if getattr(self, "enabled", False):
631
 
            self.disable_initiator_tag = (gobject.timeout_add
632
 
                                          (timedelta_to_milliseconds
633
 
                                           (timeout), self.disable))
634
 
            self.expires = datetime.datetime.utcnow() + timeout
 
423
        gobject.source_remove(self.disable_initiator_tag)
 
424
        self.disable_initiator_tag = (gobject.timeout_add
 
425
                                      (self.timeout_milliseconds(),
 
426
                                       self.disable))
635
427
    
636
428
    def need_approval(self):
637
429
        self.last_approval_request = datetime.datetime.utcnow()
653
445
        # If a checker exists, make sure it is not a zombie
654
446
        try:
655
447
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
656
 
        except (AttributeError, OSError) as error:
 
448
        except (AttributeError, OSError), error:
657
449
            if (isinstance(error, OSError)
658
450
                and error.errno != errno.ECHILD):
659
451
                raise error
677
469
                                       'replace')))
678
470
                    for attr in
679
471
                    self.runtime_expansions)
680
 
                
 
472
 
681
473
                try:
682
474
                    command = self.checker_command % escaped_attrs
683
 
                except TypeError as error:
 
475
                except TypeError, error:
684
476
                    logger.error('Could not format string "%s":'
685
477
                                 ' %s', self.checker_command, error)
686
478
                    return True # Try again later
705
497
                if pid:
706
498
                    gobject.source_remove(self.checker_callback_tag)
707
499
                    self.checker_callback(pid, status, command)
708
 
            except OSError as error:
 
500
            except OSError, error:
709
501
                logger.error("Failed to start subprocess: %s",
710
502
                             error)
711
503
        # Re-run this periodically if run by gobject.timeout_add
724
516
            #time.sleep(0.5)
725
517
            #if self.checker.poll() is None:
726
518
            #    os.kill(self.checker.pid, signal.SIGKILL)
727
 
        except OSError as error:
 
519
        except OSError, error:
728
520
            if error.errno != errno.ESRCH: # No such process
729
521
                raise
730
522
        self.checker = None
731
523
 
732
 
 
733
524
def dbus_service_property(dbus_interface, signature="v",
734
525
                          access="readwrite", byte_arrays=False):
735
526
    """Decorators for marking methods of a DBusObjectWithProperties to
781
572
 
782
573
class DBusObjectWithProperties(dbus.service.Object):
783
574
    """A D-Bus object with properties.
784
 
    
 
575
 
785
576
    Classes inheriting from this can use the dbus_service_property
786
577
    decorator to expose methods as D-Bus properties.  It exposes the
787
578
    standard Get(), Set(), and GetAll() methods on the D-Bus.
794
585
    def _get_all_dbus_properties(self):
795
586
        """Returns a generator of (name, attribute) pairs
796
587
        """
797
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
798
 
                for cls in self.__class__.__mro__
 
588
        return ((prop._dbus_name, prop)
799
589
                for name, prop in
800
 
                inspect.getmembers(cls, self._is_dbus_property))
 
590
                inspect.getmembers(self, self._is_dbus_property))
801
591
    
802
592
    def _get_dbus_property(self, interface_name, property_name):
803
593
        """Returns a bound method if one exists which is a D-Bus
804
594
        property with the specified name and interface.
805
595
        """
806
 
        for cls in  self.__class__.__mro__:
807
 
            for name, value in (inspect.getmembers
808
 
                                (cls, self._is_dbus_property)):
809
 
                if (value._dbus_name == property_name
810
 
                    and value._dbus_interface == interface_name):
811
 
                    return value.__get__(self)
812
 
        
 
596
        for name in (property_name,
 
597
                     property_name + "_dbus_property"):
 
598
            prop = getattr(self, name, None)
 
599
            if (prop is None
 
600
                or not self._is_dbus_property(prop)
 
601
                or prop._dbus_name != property_name
 
602
                or (interface_name and prop._dbus_interface
 
603
                    and interface_name != prop._dbus_interface)):
 
604
                continue
 
605
            return prop
813
606
        # No such property
814
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
815
608
                                   + interface_name + "."
849
642
    def GetAll(self, interface_name):
850
643
        """Standard D-Bus property GetAll() method, see D-Bus
851
644
        standard.
852
 
        
 
645
 
853
646
        Note: Will not include properties with access="write".
854
647
        """
855
 
        properties = {}
 
648
        all = {}
856
649
        for name, prop in self._get_all_dbus_properties():
857
650
            if (interface_name
858
651
                and interface_name != prop._dbus_interface):
863
656
                continue
864
657
            value = prop()
865
658
            if not hasattr(value, "variant_level"):
866
 
                properties[name] = value
 
659
                all[name] = value
867
660
                continue
868
 
            properties[name] = type(value)(value, variant_level=
869
 
                                           value.variant_level+1)
870
 
        return dbus.Dictionary(properties, signature="sv")
 
661
            all[name] = type(value)(value, variant_level=
 
662
                                    value.variant_level+1)
 
663
        return dbus.Dictionary(all, signature="sv")
871
664
    
872
665
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
873
666
                         out_signature="s",
911
704
            xmlstring = document.toxml("utf-8")
912
705
            document.unlink()
913
706
        except (AttributeError, xml.dom.DOMException,
914
 
                xml.parsers.expat.ExpatError) as error:
 
707
                xml.parsers.expat.ExpatError), error:
915
708
            logger.error("Failed to override Introspection method",
916
709
                         error)
917
710
        return xmlstring
918
711
 
919
712
 
920
 
def datetime_to_dbus (dt, variant_level=0):
921
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
922
 
    if dt is None:
923
 
        return dbus.String("", variant_level = variant_level)
924
 
    return dbus.String(dt.isoformat(),
925
 
                       variant_level=variant_level)
926
 
 
927
 
 
928
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
929
 
                                  .__metaclass__):
930
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
931
 
    will add additional D-Bus attributes matching a certain pattern.
932
 
    """
933
 
    def __new__(mcs, name, bases, attr):
934
 
        # Go through all the base classes which could have D-Bus
935
 
        # methods, signals, or properties in them
936
 
        for base in (b for b in bases
937
 
                     if issubclass(b, dbus.service.Object)):
938
 
            # Go though all attributes of the base class
939
 
            for attrname, attribute in inspect.getmembers(base):
940
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
941
 
                # with the wrong interface name
942
 
                if (not hasattr(attribute, "_dbus_interface")
943
 
                    or not attribute._dbus_interface
944
 
                    .startswith("se.recompile.Mandos")):
945
 
                    continue
946
 
                # Create an alternate D-Bus interface name based on
947
 
                # the current name
948
 
                alt_interface = (attribute._dbus_interface
949
 
                                 .replace("se.recompile.Mandos",
950
 
                                          "se.bsnet.fukt.Mandos"))
951
 
                # Is this a D-Bus signal?
952
 
                if getattr(attribute, "_dbus_is_signal", False):
953
 
                    # Extract the original non-method function by
954
 
                    # black magic
955
 
                    nonmethod_func = (dict(
956
 
                            zip(attribute.func_code.co_freevars,
957
 
                                attribute.__closure__))["func"]
958
 
                                      .cell_contents)
959
 
                    # Create a new, but exactly alike, function
960
 
                    # object, and decorate it to be a new D-Bus signal
961
 
                    # with the alternate D-Bus interface name
962
 
                    new_function = (dbus.service.signal
963
 
                                    (alt_interface,
964
 
                                     attribute._dbus_signature)
965
 
                                    (types.FunctionType(
966
 
                                nonmethod_func.func_code,
967
 
                                nonmethod_func.func_globals,
968
 
                                nonmethod_func.func_name,
969
 
                                nonmethod_func.func_defaults,
970
 
                                nonmethod_func.func_closure)))
971
 
                    # Define a creator of a function to call both the
972
 
                    # old and new functions, so both the old and new
973
 
                    # signals gets sent when the function is called
974
 
                    def fixscope(func1, func2):
975
 
                        """This function is a scope container to pass
976
 
                        func1 and func2 to the "call_both" function
977
 
                        outside of its arguments"""
978
 
                        def call_both(*args, **kwargs):
979
 
                            """This function will emit two D-Bus
980
 
                            signals by calling func1 and func2"""
981
 
                            func1(*args, **kwargs)
982
 
                            func2(*args, **kwargs)
983
 
                        return call_both
984
 
                    # Create the "call_both" function and add it to
985
 
                    # the class
986
 
                    attr[attrname] = fixscope(attribute,
987
 
                                              new_function)
988
 
                # Is this a D-Bus method?
989
 
                elif getattr(attribute, "_dbus_is_method", False):
990
 
                    # Create a new, but exactly alike, function
991
 
                    # object.  Decorate it to be a new D-Bus method
992
 
                    # with the alternate D-Bus interface name.  Add it
993
 
                    # to the class.
994
 
                    attr[attrname] = (dbus.service.method
995
 
                                      (alt_interface,
996
 
                                       attribute._dbus_in_signature,
997
 
                                       attribute._dbus_out_signature)
998
 
                                      (types.FunctionType
999
 
                                       (attribute.func_code,
1000
 
                                        attribute.func_globals,
1001
 
                                        attribute.func_name,
1002
 
                                        attribute.func_defaults,
1003
 
                                        attribute.func_closure)))
1004
 
                # Is this a D-Bus property?
1005
 
                elif getattr(attribute, "_dbus_is_property", False):
1006
 
                    # Create a new, but exactly alike, function
1007
 
                    # object, and decorate it to be a new D-Bus
1008
 
                    # property with the alternate D-Bus interface
1009
 
                    # name.  Add it to the class.
1010
 
                    attr[attrname] = (dbus_service_property
1011
 
                                      (alt_interface,
1012
 
                                       attribute._dbus_signature,
1013
 
                                       attribute._dbus_access,
1014
 
                                       attribute
1015
 
                                       ._dbus_get_args_options
1016
 
                                       ["byte_arrays"])
1017
 
                                      (types.FunctionType
1018
 
                                       (attribute.func_code,
1019
 
                                        attribute.func_globals,
1020
 
                                        attribute.func_name,
1021
 
                                        attribute.func_defaults,
1022
 
                                        attribute.func_closure)))
1023
 
        return type.__new__(mcs, name, bases, attr)
1024
 
 
1025
 
 
1026
713
class ClientDBus(Client, DBusObjectWithProperties):
1027
714
    """A Client class using D-Bus
1028
715
    
1037
724
    # dbus.service.Object doesn't use super(), so we can't either.
1038
725
    
1039
726
    def __init__(self, bus = None, *args, **kwargs):
 
727
        self._approvals_pending = 0
1040
728
        self.bus = bus
1041
729
        Client.__init__(self, *args, **kwargs)
1042
 
        self._approvals_pending = 0
1043
 
        
1044
 
        self._approvals_pending = 0
1045
730
        # Only now, when this client is initialized, can it show up on
1046
731
        # the D-Bus
1047
732
        client_object_name = unicode(self.name).translate(
1052
737
        DBusObjectWithProperties.__init__(self, self.bus,
1053
738
                                          self.dbus_object_path)
1054
739
        
1055
 
    def notifychangeproperty(transform_func,
1056
 
                             dbus_name, type_func=lambda x: x,
1057
 
                             variant_level=1):
1058
 
        """ Modify a variable so that it's a property which announces
1059
 
        its changes to DBus.
1060
 
        
1061
 
        transform_fun: Function that takes a value and a variant_level
1062
 
                       and transforms it to a D-Bus type.
1063
 
        dbus_name: D-Bus name of the variable
1064
 
        type_func: Function that transform the value before sending it
1065
 
                   to the D-Bus.  Default: no transform
1066
 
        variant_level: D-Bus variant level.  Default: 1
1067
 
        """
1068
 
        attrname = "_{0}".format(dbus_name)
1069
 
        def setter(self, value):
1070
 
            if hasattr(self, "dbus_object_path"):
1071
 
                if (not hasattr(self, attrname) or
1072
 
                    type_func(getattr(self, attrname, None))
1073
 
                    != type_func(value)):
1074
 
                    dbus_value = transform_func(type_func(value),
1075
 
                                                variant_level
1076
 
                                                =variant_level)
1077
 
                    self.PropertyChanged(dbus.String(dbus_name),
1078
 
                                         dbus_value)
1079
 
            setattr(self, attrname, value)
1080
 
        
1081
 
        return property(lambda self: getattr(self, attrname), setter)
1082
 
    
1083
 
    
1084
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
1085
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
1086
 
                                             "ApprovalPending",
1087
 
                                             type_func = bool)
1088
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1089
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
1090
 
                                        "LastEnabled")
1091
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1092
 
                                   type_func = lambda checker:
1093
 
                                       checker is not None)
1094
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1095
 
                                           "LastCheckedOK")
1096
 
    last_approval_request = notifychangeproperty(
1097
 
        datetime_to_dbus, "LastApprovalRequest")
1098
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
1099
 
                                               "ApprovedByDefault")
1100
 
    approval_delay = notifychangeproperty(dbus.UInt64,
1101
 
                                          "ApprovalDelay",
1102
 
                                          type_func =
1103
 
                                          timedelta_to_milliseconds)
1104
 
    approval_duration = notifychangeproperty(
1105
 
        dbus.UInt64, "ApprovalDuration",
1106
 
        type_func = timedelta_to_milliseconds)
1107
 
    host = notifychangeproperty(dbus.String, "Host")
1108
 
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1109
 
                                   type_func =
1110
 
                                   timedelta_to_milliseconds)
1111
 
    extended_timeout = notifychangeproperty(
1112
 
        dbus.UInt64, "ExtendedTimeout",
1113
 
        type_func = timedelta_to_milliseconds)
1114
 
    interval = notifychangeproperty(dbus.UInt64,
1115
 
                                    "Interval",
1116
 
                                    type_func =
1117
 
                                    timedelta_to_milliseconds)
1118
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
1119
 
    
1120
 
    del notifychangeproperty
 
740
    def _get_approvals_pending(self):
 
741
        return self._approvals_pending
 
742
    def _set_approvals_pending(self, value):
 
743
        old_value = self._approvals_pending
 
744
        self._approvals_pending = value
 
745
        bval = bool(value)
 
746
        if (hasattr(self, "dbus_object_path")
 
747
            and bval is not bool(old_value)):
 
748
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
749
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
750
                                 dbus_bool)
 
751
 
 
752
    approvals_pending = property(_get_approvals_pending,
 
753
                                 _set_approvals_pending)
 
754
    del _get_approvals_pending, _set_approvals_pending
 
755
    
 
756
    @staticmethod
 
757
    def _datetime_to_dbus(dt, variant_level=0):
 
758
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
759
        return dbus.String(dt.isoformat(),
 
760
                           variant_level=variant_level)
 
761
    
 
762
    def enable(self):
 
763
        oldstate = getattr(self, "enabled", False)
 
764
        r = Client.enable(self)
 
765
        if oldstate != self.enabled:
 
766
            # Emit D-Bus signals
 
767
            self.PropertyChanged(dbus.String("Enabled"),
 
768
                                 dbus.Boolean(True, variant_level=1))
 
769
            self.PropertyChanged(
 
770
                dbus.String("LastEnabled"),
 
771
                self._datetime_to_dbus(self.last_enabled,
 
772
                                       variant_level=1))
 
773
        return r
 
774
    
 
775
    def disable(self, quiet = False):
 
776
        oldstate = getattr(self, "enabled", False)
 
777
        r = Client.disable(self, quiet=quiet)
 
778
        if not quiet and oldstate != self.enabled:
 
779
            # Emit D-Bus signal
 
780
            self.PropertyChanged(dbus.String("Enabled"),
 
781
                                 dbus.Boolean(False, variant_level=1))
 
782
        return r
1121
783
    
1122
784
    def __del__(self, *args, **kwargs):
1123
785
        try:
1132
794
                         *args, **kwargs):
1133
795
        self.checker_callback_tag = None
1134
796
        self.checker = None
 
797
        # Emit D-Bus signal
 
798
        self.PropertyChanged(dbus.String("CheckerRunning"),
 
799
                             dbus.Boolean(False, variant_level=1))
1135
800
        if os.WIFEXITED(condition):
1136
801
            exitstatus = os.WEXITSTATUS(condition)
1137
802
            # Emit D-Bus signal
1147
812
        return Client.checker_callback(self, pid, condition, command,
1148
813
                                       *args, **kwargs)
1149
814
    
 
815
    def checked_ok(self, *args, **kwargs):
 
816
        r = Client.checked_ok(self, *args, **kwargs)
 
817
        # Emit D-Bus signal
 
818
        self.PropertyChanged(
 
819
            dbus.String("LastCheckedOK"),
 
820
            (self._datetime_to_dbus(self.last_checked_ok,
 
821
                                    variant_level=1)))
 
822
        return r
 
823
    
 
824
    def need_approval(self, *args, **kwargs):
 
825
        r = Client.need_approval(self, *args, **kwargs)
 
826
        # Emit D-Bus signal
 
827
        self.PropertyChanged(
 
828
            dbus.String("LastApprovalRequest"),
 
829
            (self._datetime_to_dbus(self.last_approval_request,
 
830
                                    variant_level=1)))
 
831
        return r
 
832
    
1150
833
    def start_checker(self, *args, **kwargs):
1151
834
        old_checker = self.checker
1152
835
        if self.checker is not None:
1159
842
            and old_checker_pid != self.checker.pid):
1160
843
            # Emit D-Bus signal
1161
844
            self.CheckerStarted(self.current_checker_command)
 
845
            self.PropertyChanged(
 
846
                dbus.String("CheckerRunning"),
 
847
                dbus.Boolean(True, variant_level=1))
1162
848
        return r
1163
849
    
 
850
    def stop_checker(self, *args, **kwargs):
 
851
        old_checker = getattr(self, "checker", None)
 
852
        r = Client.stop_checker(self, *args, **kwargs)
 
853
        if (old_checker is not None
 
854
            and getattr(self, "checker", None) is None):
 
855
            self.PropertyChanged(dbus.String("CheckerRunning"),
 
856
                                 dbus.Boolean(False, variant_level=1))
 
857
        return r
 
858
 
1164
859
    def _reset_approved(self):
1165
 
        self.approved = None
 
860
        self._approved = None
1166
861
        return False
1167
862
    
1168
863
    def approve(self, value=True):
1169
864
        self.send_changedstate()
1170
 
        self.approved = value
1171
 
        gobject.timeout_add(timedelta_to_milliseconds
 
865
        self._approved = value
 
866
        gobject.timeout_add(self._timedelta_to_milliseconds
1172
867
                            (self.approval_duration),
1173
868
                            self._reset_approved)
1174
869
    
1175
870
    
1176
871
    ## D-Bus methods, signals & properties
1177
 
    _interface = "se.recompile.Mandos.Client"
 
872
    _interface = "se.bsnet.fukt.Mandos.Client"
1178
873
    
1179
874
    ## Signals
1180
875
    
1217
912
        "D-Bus signal"
1218
913
        return self.need_approval()
1219
914
    
1220
 
    # NeRwequest - signal
1221
 
    @dbus.service.signal(_interface, signature="s")
1222
 
    def NewRequest(self, ip):
1223
 
        """D-Bus signal
1224
 
        Is sent after a client request a password.
1225
 
        """
1226
 
        pass
1227
 
    
1228
915
    ## Methods
1229
916
    
1230
917
    # Approve - method
1235
922
    # CheckedOK - method
1236
923
    @dbus.service.method(_interface)
1237
924
    def CheckedOK(self):
1238
 
        self.checked_ok()
 
925
        return self.checked_ok()
1239
926
    
1240
927
    # Enable - method
1241
928
    @dbus.service.method(_interface)
1274
961
        if value is None:       # get
1275
962
            return dbus.Boolean(self.approved_by_default)
1276
963
        self.approved_by_default = bool(value)
 
964
        # Emit D-Bus signal
 
965
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
 
966
                             dbus.Boolean(value, variant_level=1))
1277
967
    
1278
968
    # ApprovalDelay - property
1279
969
    @dbus_service_property(_interface, signature="t",
1282
972
        if value is None:       # get
1283
973
            return dbus.UInt64(self.approval_delay_milliseconds())
1284
974
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
975
        # Emit D-Bus signal
 
976
        self.PropertyChanged(dbus.String("ApprovalDelay"),
 
977
                             dbus.UInt64(value, variant_level=1))
1285
978
    
1286
979
    # ApprovalDuration - property
1287
980
    @dbus_service_property(_interface, signature="t",
1288
981
                           access="readwrite")
1289
982
    def ApprovalDuration_dbus_property(self, value=None):
1290
983
        if value is None:       # get
1291
 
            return dbus.UInt64(timedelta_to_milliseconds(
 
984
            return dbus.UInt64(self._timedelta_to_milliseconds(
1292
985
                    self.approval_duration))
1293
986
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
987
        # Emit D-Bus signal
 
988
        self.PropertyChanged(dbus.String("ApprovalDuration"),
 
989
                             dbus.UInt64(value, variant_level=1))
1294
990
    
1295
991
    # Name - property
1296
992
    @dbus_service_property(_interface, signature="s", access="read")
1308
1004
    def Host_dbus_property(self, value=None):
1309
1005
        if value is None:       # get
1310
1006
            return dbus.String(self.host)
1311
 
        self.host = unicode(value)
 
1007
        self.host = value
 
1008
        # Emit D-Bus signal
 
1009
        self.PropertyChanged(dbus.String("Host"),
 
1010
                             dbus.String(value, variant_level=1))
1312
1011
    
1313
1012
    # Created - property
1314
1013
    @dbus_service_property(_interface, signature="s", access="read")
1315
1014
    def Created_dbus_property(self):
1316
 
        return datetime_to_dbus(self.created)
 
1015
        return dbus.String(self._datetime_to_dbus(self.created))
1317
1016
    
1318
1017
    # LastEnabled - property
1319
1018
    @dbus_service_property(_interface, signature="s", access="read")
1320
1019
    def LastEnabled_dbus_property(self):
1321
 
        return datetime_to_dbus(self.last_enabled)
 
1020
        if self.last_enabled is None:
 
1021
            return dbus.String("")
 
1022
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1322
1023
    
1323
1024
    # Enabled - property
1324
1025
    @dbus_service_property(_interface, signature="b",
1338
1039
        if value is not None:
1339
1040
            self.checked_ok()
1340
1041
            return
1341
 
        return datetime_to_dbus(self.last_checked_ok)
1342
 
    
1343
 
    # Expires - property
1344
 
    @dbus_service_property(_interface, signature="s", access="read")
1345
 
    def Expires_dbus_property(self):
1346
 
        return datetime_to_dbus(self.expires)
 
1042
        if self.last_checked_ok is None:
 
1043
            return dbus.String("")
 
1044
        return dbus.String(self._datetime_to_dbus(self
 
1045
                                                  .last_checked_ok))
1347
1046
    
1348
1047
    # LastApprovalRequest - property
1349
1048
    @dbus_service_property(_interface, signature="s", access="read")
1350
1049
    def LastApprovalRequest_dbus_property(self):
1351
 
        return datetime_to_dbus(self.last_approval_request)
 
1050
        if self.last_approval_request is None:
 
1051
            return dbus.String("")
 
1052
        return dbus.String(self.
 
1053
                           _datetime_to_dbus(self
 
1054
                                             .last_approval_request))
1352
1055
    
1353
1056
    # Timeout - property
1354
1057
    @dbus_service_property(_interface, signature="t",
1357
1060
        if value is None:       # get
1358
1061
            return dbus.UInt64(self.timeout_milliseconds())
1359
1062
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1063
        # Emit D-Bus signal
 
1064
        self.PropertyChanged(dbus.String("Timeout"),
 
1065
                             dbus.UInt64(value, variant_level=1))
1360
1066
        if getattr(self, "disable_initiator_tag", None) is None:
1361
1067
            return
1362
1068
        # Reschedule timeout
1363
1069
        gobject.source_remove(self.disable_initiator_tag)
1364
1070
        self.disable_initiator_tag = None
1365
 
        self.expires = None
1366
 
        time_to_die = timedelta_to_milliseconds((self
1367
 
                                                 .last_checked_ok
1368
 
                                                 + self.timeout)
1369
 
                                                - datetime.datetime
1370
 
                                                .utcnow())
 
1071
        time_to_die = (self.
 
1072
                       _timedelta_to_milliseconds((self
 
1073
                                                   .last_checked_ok
 
1074
                                                   + self.timeout)
 
1075
                                                  - datetime.datetime
 
1076
                                                  .utcnow()))
1371
1077
        if time_to_die <= 0:
1372
1078
            # The timeout has passed
1373
1079
            self.disable()
1374
1080
        else:
1375
 
            self.expires = (datetime.datetime.utcnow()
1376
 
                            + datetime.timedelta(milliseconds =
1377
 
                                                 time_to_die))
1378
1081
            self.disable_initiator_tag = (gobject.timeout_add
1379
1082
                                          (time_to_die, self.disable))
1380
1083
    
1381
 
    # ExtendedTimeout - property
1382
 
    @dbus_service_property(_interface, signature="t",
1383
 
                           access="readwrite")
1384
 
    def ExtendedTimeout_dbus_property(self, value=None):
1385
 
        if value is None:       # get
1386
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
1387
 
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1388
 
    
1389
1084
    # Interval - property
1390
1085
    @dbus_service_property(_interface, signature="t",
1391
1086
                           access="readwrite")
1393
1088
        if value is None:       # get
1394
1089
            return dbus.UInt64(self.interval_milliseconds())
1395
1090
        self.interval = datetime.timedelta(0, 0, 0, value)
 
1091
        # Emit D-Bus signal
 
1092
        self.PropertyChanged(dbus.String("Interval"),
 
1093
                             dbus.UInt64(value, variant_level=1))
1396
1094
        if getattr(self, "checker_initiator_tag", None) is None:
1397
1095
            return
1398
 
        if self.enabled:
1399
 
            # Reschedule checker run
1400
 
            gobject.source_remove(self.checker_initiator_tag)
1401
 
            self.checker_initiator_tag = (gobject.timeout_add
1402
 
                                          (value, self.start_checker))
1403
 
            self.start_checker()    # Start one now, too
1404
 
    
 
1096
        # Reschedule checker run
 
1097
        gobject.source_remove(self.checker_initiator_tag)
 
1098
        self.checker_initiator_tag = (gobject.timeout_add
 
1099
                                      (value, self.start_checker))
 
1100
        self.start_checker()    # Start one now, too
 
1101
 
1405
1102
    # Checker - property
1406
1103
    @dbus_service_property(_interface, signature="s",
1407
1104
                           access="readwrite")
1408
1105
    def Checker_dbus_property(self, value=None):
1409
1106
        if value is None:       # get
1410
1107
            return dbus.String(self.checker_command)
1411
 
        self.checker_command = unicode(value)
 
1108
        self.checker_command = value
 
1109
        # Emit D-Bus signal
 
1110
        self.PropertyChanged(dbus.String("Checker"),
 
1111
                             dbus.String(self.checker_command,
 
1112
                                         variant_level=1))
1412
1113
    
1413
1114
    # CheckerRunning - property
1414
1115
    @dbus_service_property(_interface, signature="b",
1441
1142
        self._pipe.send(('init', fpr, address))
1442
1143
        if not self._pipe.recv():
1443
1144
            raise KeyError()
1444
 
    
 
1145
 
1445
1146
    def __getattribute__(self, name):
1446
 
        if name == '_pipe':
 
1147
        if(name == '_pipe'):
1447
1148
            return super(ProxyClient, self).__getattribute__(name)
1448
1149
        self._pipe.send(('getattr', name))
1449
1150
        data = self._pipe.recv()
1454
1155
                self._pipe.send(('funcall', name, args, kwargs))
1455
1156
                return self._pipe.recv()[1]
1456
1157
            return func
1457
 
    
 
1158
 
1458
1159
    def __setattr__(self, name, value):
1459
 
        if name == '_pipe':
 
1160
        if(name == '_pipe'):
1460
1161
            return super(ProxyClient, self).__setattr__(name, value)
1461
1162
        self._pipe.send(('setattr', name, value))
1462
1163
 
1463
1164
 
1464
 
class ClientDBusTransitional(ClientDBus):
1465
 
    __metaclass__ = AlternateDBusNamesMetaclass
1466
 
 
1467
 
 
1468
1165
class ClientHandler(socketserver.BaseRequestHandler, object):
1469
1166
    """A class to handle client connections.
1470
1167
    
1477
1174
                        unicode(self.client_address))
1478
1175
            logger.debug("Pipe FD: %d",
1479
1176
                         self.server.child_pipe.fileno())
1480
 
            
 
1177
 
1481
1178
            session = (gnutls.connection
1482
1179
                       .ClientSession(self.request,
1483
1180
                                      gnutls.connection
1484
1181
                                      .X509Credentials()))
1485
 
            
 
1182
 
1486
1183
            # Note: gnutls.connection.X509Credentials is really a
1487
1184
            # generic GnuTLS certificate credentials object so long as
1488
1185
            # no X.509 keys are added to it.  Therefore, we can use it
1489
1186
            # here despite using OpenPGP certificates.
1490
 
            
 
1187
 
1491
1188
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1492
1189
            #                      "+AES-256-CBC", "+SHA1",
1493
1190
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1499
1196
            (gnutls.library.functions
1500
1197
             .gnutls_priority_set_direct(session._c_object,
1501
1198
                                         priority, None))
1502
 
            
 
1199
 
1503
1200
            # Start communication using the Mandos protocol
1504
1201
            # Get protocol number
1505
1202
            line = self.request.makefile().readline()
1507
1204
            try:
1508
1205
                if int(line.strip().split()[0]) > 1:
1509
1206
                    raise RuntimeError
1510
 
            except (ValueError, IndexError, RuntimeError) as error:
 
1207
            except (ValueError, IndexError, RuntimeError), error:
1511
1208
                logger.error("Unknown protocol version: %s", error)
1512
1209
                return
1513
 
            
 
1210
 
1514
1211
            # Start GnuTLS connection
1515
1212
            try:
1516
1213
                session.handshake()
1517
 
            except gnutls.errors.GNUTLSError as error:
 
1214
            except gnutls.errors.GNUTLSError, error:
1518
1215
                logger.warning("Handshake failed: %s", error)
1519
1216
                # Do not run session.bye() here: the session is not
1520
1217
                # established.  Just abandon the request.
1521
1218
                return
1522
1219
            logger.debug("Handshake succeeded")
1523
 
            
 
1220
 
1524
1221
            approval_required = False
1525
1222
            try:
1526
1223
                try:
1527
1224
                    fpr = self.fingerprint(self.peer_certificate
1528
1225
                                           (session))
1529
 
                except (TypeError,
1530
 
                        gnutls.errors.GNUTLSError) as error:
 
1226
                except (TypeError, gnutls.errors.GNUTLSError), error:
1531
1227
                    logger.warning("Bad certificate: %s", error)
1532
1228
                    return
1533
1229
                logger.debug("Fingerprint: %s", fpr)
1534
 
                
 
1230
 
1535
1231
                try:
1536
1232
                    client = ProxyClient(child_pipe, fpr,
1537
1233
                                         self.client_address)
1538
1234
                except KeyError:
1539
1235
                    return
1540
1236
                
1541
 
                if self.server.use_dbus:
1542
 
                    # Emit D-Bus signal
1543
 
                    client.NewRequest(str(self.client_address))
1544
 
                
1545
1237
                if client.approval_delay:
1546
1238
                    delay = client.approval_delay
1547
1239
                    client.approvals_pending += 1
1549
1241
                
1550
1242
                while True:
1551
1243
                    if not client.enabled:
1552
 
                        logger.info("Client %s is disabled",
 
1244
                        logger.warning("Client %s is disabled",
1553
1245
                                       client.name)
1554
1246
                        if self.server.use_dbus:
1555
1247
                            # Emit D-Bus signal
1556
 
                            client.Rejected("Disabled")
 
1248
                            client.Rejected("Disabled")                    
1557
1249
                        return
1558
1250
                    
1559
 
                    if client.approved or not client.approval_delay:
 
1251
                    if client._approved or not client.approval_delay:
1560
1252
                        #We are approved or approval is disabled
1561
1253
                        break
1562
 
                    elif client.approved is None:
 
1254
                    elif client._approved is None:
1563
1255
                        logger.info("Client %s needs approval",
1564
1256
                                    client.name)
1565
1257
                        if self.server.use_dbus:
1576
1268
                        return
1577
1269
                    
1578
1270
                    #wait until timeout or approved
 
1271
                    #x = float(client._timedelta_to_milliseconds(delay))
1579
1272
                    time = datetime.datetime.now()
1580
1273
                    client.changedstate.acquire()
1581
 
                    (client.changedstate.wait
1582
 
                     (float(client.timedelta_to_milliseconds(delay)
1583
 
                            / 1000)))
 
1274
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1584
1275
                    client.changedstate.release()
1585
1276
                    time2 = datetime.datetime.now()
1586
1277
                    if (time2 - time) >= delay:
1601
1292
                while sent_size < len(client.secret):
1602
1293
                    try:
1603
1294
                        sent = session.send(client.secret[sent_size:])
1604
 
                    except gnutls.errors.GNUTLSError as error:
 
1295
                    except (gnutls.errors.GNUTLSError), error:
1605
1296
                        logger.warning("gnutls send failed")
1606
1297
                        return
1607
1298
                    logger.debug("Sent: %d, remaining: %d",
1608
1299
                                 sent, len(client.secret)
1609
1300
                                 - (sent_size + sent))
1610
1301
                    sent_size += sent
1611
 
                
 
1302
 
1612
1303
                logger.info("Sending secret to %s", client.name)
1613
 
                # bump the timeout using extended_timeout
1614
 
                client.checked_ok(client.extended_timeout)
 
1304
                # bump the timeout as if seen
 
1305
                client.checked_ok()
1615
1306
                if self.server.use_dbus:
1616
1307
                    # Emit D-Bus signal
1617
1308
                    client.GotSecret()
1621
1312
                    client.approvals_pending -= 1
1622
1313
                try:
1623
1314
                    session.bye()
1624
 
                except gnutls.errors.GNUTLSError as error:
 
1315
                except (gnutls.errors.GNUTLSError), error:
1625
1316
                    logger.warning("GnuTLS bye failed")
1626
1317
    
1627
1318
    @staticmethod
1684
1375
        # Convert the buffer to a Python bytestring
1685
1376
        fpr = ctypes.string_at(buf, buf_len.value)
1686
1377
        # Convert the bytestring to hexadecimal notation
1687
 
        hex_fpr = binascii.hexlify(fpr).upper()
 
1378
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1688
1379
        return hex_fpr
1689
1380
 
1690
1381
 
1693
1384
    def sub_process_main(self, request, address):
1694
1385
        try:
1695
1386
            self.finish_request(request, address)
1696
 
        except Exception:
 
1387
        except:
1697
1388
            self.handle_error(request, address)
1698
1389
        self.close_request(request)
1699
 
    
 
1390
            
1700
1391
    def process_request(self, request, address):
1701
1392
        """Start a new process to process the request."""
1702
 
        proc = multiprocessing.Process(target = self.sub_process_main,
1703
 
                                       args = (request,
1704
 
                                               address))
1705
 
        proc.start()
1706
 
        return proc
1707
 
 
 
1393
        multiprocessing.Process(target = self.sub_process_main,
 
1394
                                args = (request, address)).start()
1708
1395
 
1709
1396
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1710
1397
    """ adds a pipe to the MixIn """
1714
1401
        This function creates a new pipe in self.pipe
1715
1402
        """
1716
1403
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1717
 
        
1718
 
        proc = MultiprocessingMixIn.process_request(self, request,
1719
 
                                                    client_address)
 
1404
 
 
1405
        super(MultiprocessingMixInWithPipe,
 
1406
              self).process_request(request, client_address)
1720
1407
        self.child_pipe.close()
1721
 
        self.add_pipe(parent_pipe, proc)
1722
 
    
1723
 
    def add_pipe(self, parent_pipe, proc):
 
1408
        self.add_pipe(parent_pipe)
 
1409
 
 
1410
    def add_pipe(self, parent_pipe):
1724
1411
        """Dummy function; override as necessary"""
1725
1412
        raise NotImplementedError
1726
1413
 
1727
 
 
1728
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1729
1415
                     socketserver.TCPServer, object):
1730
1416
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1756
1442
                                           SO_BINDTODEVICE,
1757
1443
                                           str(self.interface
1758
1444
                                               + '\0'))
1759
 
                except socket.error as error:
 
1445
                except socket.error, error:
1760
1446
                    if error[0] == errno.EPERM:
1761
1447
                        logger.error("No permission to"
1762
1448
                                     " bind to interface %s",
1804
1490
        self.enabled = False
1805
1491
        self.clients = clients
1806
1492
        if self.clients is None:
1807
 
            self.clients = {}
 
1493
            self.clients = set()
1808
1494
        self.use_dbus = use_dbus
1809
1495
        self.gnutls_priority = gnutls_priority
1810
1496
        IPv6_TCPServer.__init__(self, server_address,
1814
1500
    def server_activate(self):
1815
1501
        if self.enabled:
1816
1502
            return socketserver.TCPServer.server_activate(self)
1817
 
    
1818
1503
    def enable(self):
1819
1504
        self.enabled = True
1820
 
    
1821
 
    def add_pipe(self, parent_pipe, proc):
 
1505
    def add_pipe(self, parent_pipe):
1822
1506
        # Call "handle_ipc" for both data and EOF events
1823
1507
        gobject.io_add_watch(parent_pipe.fileno(),
1824
1508
                             gobject.IO_IN | gobject.IO_HUP,
1825
1509
                             functools.partial(self.handle_ipc,
1826
 
                                               parent_pipe =
1827
 
                                               parent_pipe,
1828
 
                                               proc = proc))
1829
 
    
 
1510
                                               parent_pipe = parent_pipe))
 
1511
        
1830
1512
    def handle_ipc(self, source, condition, parent_pipe=None,
1831
 
                   proc = None, client_object=None):
 
1513
                   client_object=None):
1832
1514
        condition_names = {
1833
1515
            gobject.IO_IN: "IN",   # There is data to read.
1834
1516
            gobject.IO_OUT: "OUT", # Data can be written (without
1843
1525
                                       for cond, name in
1844
1526
                                       condition_names.iteritems()
1845
1527
                                       if cond & condition)
1846
 
        # error, or the other end of multiprocessing.Pipe has closed
 
1528
        # error or the other end of multiprocessing.Pipe has closed
1847
1529
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1848
 
            # Wait for other process to exit
1849
 
            proc.join()
1850
1530
            return False
1851
1531
        
1852
1532
        # Read a request from the child
1857
1537
            fpr = request[1]
1858
1538
            address = request[2]
1859
1539
            
1860
 
            for c in self.clients.itervalues():
 
1540
            for c in self.clients:
1861
1541
                if c.fingerprint == fpr:
1862
1542
                    client = c
1863
1543
                    break
1864
1544
            else:
1865
 
                logger.info("Client not found for fingerprint: %s, ad"
1866
 
                            "dress: %s", fpr, address)
 
1545
                logger.warning("Client not found for fingerprint: %s, ad"
 
1546
                               "dress: %s", fpr, address)
1867
1547
                if self.use_dbus:
1868
1548
                    # Emit D-Bus signal
1869
 
                    mandos_dbus_service.ClientNotFound(fpr,
1870
 
                                                       address[0])
 
1549
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1871
1550
                parent_pipe.send(False)
1872
1551
                return False
1873
1552
            
1874
1553
            gobject.io_add_watch(parent_pipe.fileno(),
1875
1554
                                 gobject.IO_IN | gobject.IO_HUP,
1876
1555
                                 functools.partial(self.handle_ipc,
1877
 
                                                   parent_pipe =
1878
 
                                                   parent_pipe,
1879
 
                                                   proc = proc,
1880
 
                                                   client_object =
1881
 
                                                   client))
 
1556
                                                   parent_pipe = parent_pipe,
 
1557
                                                   client_object = client))
1882
1558
            parent_pipe.send(True)
1883
 
            # remove the old hook in favor of the new above hook on
1884
 
            # same fileno
 
1559
            # remove the old hook in favor of the new above hook on same fileno
1885
1560
            return False
1886
1561
        if command == 'funcall':
1887
1562
            funcname = request[1]
1888
1563
            args = request[2]
1889
1564
            kwargs = request[3]
1890
1565
            
1891
 
            parent_pipe.send(('data', getattr(client_object,
1892
 
                                              funcname)(*args,
1893
 
                                                         **kwargs)))
1894
 
        
 
1566
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1567
 
1895
1568
        if command == 'getattr':
1896
1569
            attrname = request[1]
1897
1570
            if callable(client_object.__getattribute__(attrname)):
1898
1571
                parent_pipe.send(('function',))
1899
1572
            else:
1900
 
                parent_pipe.send(('data', client_object
1901
 
                                  .__getattribute__(attrname)))
 
1573
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1902
1574
        
1903
1575
        if command == 'setattr':
1904
1576
            attrname = request[1]
1905
1577
            value = request[2]
1906
1578
            setattr(client_object, attrname, value)
1907
 
        
 
1579
 
1908
1580
        return True
1909
1581
 
1910
1582
 
1941
1613
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1942
1614
            else:
1943
1615
                raise ValueError("Unknown suffix %r" % suffix)
1944
 
        except (ValueError, IndexError) as e:
 
1616
        except (ValueError, IndexError), e:
1945
1617
            raise ValueError(*(e.args))
1946
1618
        timevalue += delta
1947
1619
    return timevalue
1948
1620
 
1949
1621
 
 
1622
def if_nametoindex(interface):
 
1623
    """Call the C function if_nametoindex(), or equivalent
 
1624
    
 
1625
    Note: This function cannot accept a unicode string."""
 
1626
    global if_nametoindex
 
1627
    try:
 
1628
        if_nametoindex = (ctypes.cdll.LoadLibrary
 
1629
                          (ctypes.util.find_library("c"))
 
1630
                          .if_nametoindex)
 
1631
    except (OSError, AttributeError):
 
1632
        logger.warning("Doing if_nametoindex the hard way")
 
1633
        def if_nametoindex(interface):
 
1634
            "Get an interface index the hard way, i.e. using fcntl()"
 
1635
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
 
1636
            with contextlib.closing(socket.socket()) as s:
 
1637
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
1638
                                    struct.pack(str("16s16x"),
 
1639
                                                interface))
 
1640
            interface_index = struct.unpack(str("I"),
 
1641
                                            ifreq[16:20])[0]
 
1642
            return interface_index
 
1643
    return if_nametoindex(interface)
 
1644
 
 
1645
 
1950
1646
def daemon(nochdir = False, noclose = False):
1951
1647
    """See daemon(3).  Standard BSD Unix function.
1952
1648
    
1977
1673
    ##################################################################
1978
1674
    # Parsing of options, both command line and config file
1979
1675
    
1980
 
    parser = argparse.ArgumentParser()
1981
 
    parser.add_argument("-v", "--version", action="version",
1982
 
                        version = "%%(prog)s %s" % version,
1983
 
                        help="show version number and exit")
1984
 
    parser.add_argument("-i", "--interface", metavar="IF",
1985
 
                        help="Bind to interface IF")
1986
 
    parser.add_argument("-a", "--address",
1987
 
                        help="Address to listen for requests on")
1988
 
    parser.add_argument("-p", "--port", type=int,
1989
 
                        help="Port number to receive requests on")
1990
 
    parser.add_argument("--check", action="store_true",
1991
 
                        help="Run self-test")
1992
 
    parser.add_argument("--debug", action="store_true",
1993
 
                        help="Debug mode; run in foreground and log"
1994
 
                        " to terminal")
1995
 
    parser.add_argument("--debuglevel", metavar="LEVEL",
1996
 
                        help="Debug level for stdout output")
1997
 
    parser.add_argument("--priority", help="GnuTLS"
1998
 
                        " priority string (see GnuTLS documentation)")
1999
 
    parser.add_argument("--servicename",
2000
 
                        metavar="NAME", help="Zeroconf service name")
2001
 
    parser.add_argument("--configdir",
2002
 
                        default="/etc/mandos", metavar="DIR",
2003
 
                        help="Directory to search for configuration"
2004
 
                        " files")
2005
 
    parser.add_argument("--no-dbus", action="store_false",
2006
 
                        dest="use_dbus", help="Do not provide D-Bus"
2007
 
                        " system bus interface")
2008
 
    parser.add_argument("--no-ipv6", action="store_false",
2009
 
                        dest="use_ipv6", help="Do not use IPv6")
2010
 
    parser.add_argument("--no-restore", action="store_false",
2011
 
                        dest="restore", help="Do not restore stored"
2012
 
                        " state")
2013
 
    parser.add_argument("--statedir", metavar="DIR",
2014
 
                        help="Directory to save/restore state in")
2015
 
    
2016
 
    options = parser.parse_args()
 
1676
    parser = optparse.OptionParser(version = "%%prog %s" % version)
 
1677
    parser.add_option("-i", "--interface", type="string",
 
1678
                      metavar="IF", help="Bind to interface IF")
 
1679
    parser.add_option("-a", "--address", type="string",
 
1680
                      help="Address to listen for requests on")
 
1681
    parser.add_option("-p", "--port", type="int",
 
1682
                      help="Port number to receive requests on")
 
1683
    parser.add_option("--check", action="store_true",
 
1684
                      help="Run self-test")
 
1685
    parser.add_option("--debug", action="store_true",
 
1686
                      help="Debug mode; run in foreground and log to"
 
1687
                      " terminal")
 
1688
    parser.add_option("--debuglevel", type="string", metavar="LEVEL",
 
1689
                      help="Debug level for stdout output")
 
1690
    parser.add_option("--priority", type="string", help="GnuTLS"
 
1691
                      " priority string (see GnuTLS documentation)")
 
1692
    parser.add_option("--servicename", type="string",
 
1693
                      metavar="NAME", help="Zeroconf service name")
 
1694
    parser.add_option("--configdir", type="string",
 
1695
                      default="/etc/mandos", metavar="DIR",
 
1696
                      help="Directory to search for configuration"
 
1697
                      " files")
 
1698
    parser.add_option("--no-dbus", action="store_false",
 
1699
                      dest="use_dbus", help="Do not provide D-Bus"
 
1700
                      " system bus interface")
 
1701
    parser.add_option("--no-ipv6", action="store_false",
 
1702
                      dest="use_ipv6", help="Do not use IPv6")
 
1703
    options = parser.parse_args()[0]
2017
1704
    
2018
1705
    if options.check:
2019
1706
        import doctest
2031
1718
                        "use_dbus": "True",
2032
1719
                        "use_ipv6": "True",
2033
1720
                        "debuglevel": "",
2034
 
                        "restore": "True",
2035
 
                        "statedir": "/var/lib/mandos"
2036
1721
                        }
2037
1722
    
2038
1723
    # Parse config file for server-global settings
2055
1740
    # options, if set.
2056
1741
    for option in ("interface", "address", "port", "debug",
2057
1742
                   "priority", "servicename", "configdir",
2058
 
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2059
 
                   "statedir"):
 
1743
                   "use_dbus", "use_ipv6", "debuglevel"):
2060
1744
        value = getattr(options, option)
2061
1745
        if value is not None:
2062
1746
            server_settings[option] = value
2074
1758
    debuglevel = server_settings["debuglevel"]
2075
1759
    use_dbus = server_settings["use_dbus"]
2076
1760
    use_ipv6 = server_settings["use_ipv6"]
2077
 
    stored_state_path = os.path.join(server_settings["statedir"],
2078
 
                                     stored_state_file)
2079
 
    
2080
 
    if debug:
2081
 
        initlogger(logging.DEBUG)
2082
 
    else:
2083
 
        if not debuglevel:
2084
 
            initlogger()
2085
 
        else:
2086
 
            level = getattr(logging, debuglevel.upper())
2087
 
            initlogger(level)
2088
 
    
 
1761
 
2089
1762
    if server_settings["servicename"] != "Mandos":
2090
1763
        syslogger.setFormatter(logging.Formatter
2091
1764
                               ('Mandos (%s) [%%(process)d]:'
2093
1766
                                % server_settings["servicename"]))
2094
1767
    
2095
1768
    # Parse config file with clients
2096
 
    client_config = configparser.SafeConfigParser(Client.client_defaults)
 
1769
    client_defaults = { "timeout": "1h",
 
1770
                        "interval": "5m",
 
1771
                        "checker": "fping -q -- %%(host)s",
 
1772
                        "host": "",
 
1773
                        "approval_delay": "0s",
 
1774
                        "approval_duration": "1s",
 
1775
                        }
 
1776
    client_config = configparser.SafeConfigParser(client_defaults)
2097
1777
    client_config.read(os.path.join(server_settings["configdir"],
2098
1778
                                    "clients.conf"))
2099
1779
    
2133
1813
    try:
2134
1814
        os.setgid(gid)
2135
1815
        os.setuid(uid)
2136
 
    except OSError as error:
 
1816
    except OSError, error:
2137
1817
        if error[0] != errno.EPERM:
2138
1818
            raise error
2139
1819
    
 
1820
    if not debug and not debuglevel:
 
1821
        syslogger.setLevel(logging.WARNING)
 
1822
        console.setLevel(logging.WARNING)
 
1823
    if debuglevel:
 
1824
        level = getattr(logging, debuglevel.upper())
 
1825
        syslogger.setLevel(level)
 
1826
        console.setLevel(level)
 
1827
 
2140
1828
    if debug:
2141
1829
        # Enable all possible GnuTLS debugging
2142
1830
        
2173
1861
    # End of Avahi example code
2174
1862
    if use_dbus:
2175
1863
        try:
2176
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1864
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2177
1865
                                            bus, do_not_queue=True)
2178
 
            old_bus_name = (dbus.service.BusName
2179
 
                            ("se.bsnet.fukt.Mandos", bus,
2180
 
                             do_not_queue=True))
2181
 
        except dbus.exceptions.NameExistsException as e:
 
1866
        except dbus.exceptions.NameExistsException, e:
2182
1867
            logger.error(unicode(e) + ", disabling D-Bus")
2183
1868
            use_dbus = False
2184
1869
            server_settings["use_dbus"] = False
2185
1870
            tcp_server.use_dbus = False
2186
1871
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2187
 
    service = AvahiServiceToSyslog(name =
2188
 
                                   server_settings["servicename"],
2189
 
                                   servicetype = "_mandos._tcp",
2190
 
                                   protocol = protocol, bus = bus)
 
1872
    service = AvahiService(name = server_settings["servicename"],
 
1873
                           servicetype = "_mandos._tcp",
 
1874
                           protocol = protocol, bus = bus)
2191
1875
    if server_settings["interface"]:
2192
1876
        service.interface = (if_nametoindex
2193
1877
                             (str(server_settings["interface"])))
2197
1881
    
2198
1882
    client_class = Client
2199
1883
    if use_dbus:
2200
 
        client_class = functools.partial(ClientDBusTransitional,
2201
 
                                         bus = bus)
2202
 
    
2203
 
    client_settings = Client.config_parser(client_config)
2204
 
    old_client_settings = {}
2205
 
    clients_data = {}
2206
 
    
2207
 
    # Get client data and settings from last running state.
2208
 
    if server_settings["restore"]:
2209
 
        try:
2210
 
            with open(stored_state_path, "rb") as stored_state:
2211
 
                clients_data, old_client_settings = (pickle.load
2212
 
                                                     (stored_state))
2213
 
            os.remove(stored_state_path)
2214
 
        except IOError as e:
2215
 
            logger.warning("Could not load persistent state: {0}"
2216
 
                           .format(e))
2217
 
            if e.errno != errno.ENOENT:
2218
 
                raise
2219
 
    
2220
 
    with PGPEngine() as pgp:
2221
 
        for client_name, client in clients_data.iteritems():
2222
 
            # Decide which value to use after restoring saved state.
2223
 
            # We have three different values: Old config file,
2224
 
            # new config file, and saved state.
2225
 
            # New config value takes precedence if it differs from old
2226
 
            # config value, otherwise use saved state.
2227
 
            for name, value in client_settings[client_name].items():
2228
 
                try:
2229
 
                    # For each value in new config, check if it
2230
 
                    # differs from the old config value (Except for
2231
 
                    # the "secret" attribute)
2232
 
                    if (name != "secret" and
2233
 
                        value != old_client_settings[client_name]
2234
 
                        [name]):
2235
 
                        client[name] = value
2236
 
                except KeyError:
2237
 
                    pass
2238
 
            
2239
 
            # Clients who has passed its expire date can still be
2240
 
            # enabled if its last checker was successful.  Clients
2241
 
            # whose checker failed before we stored its state is
2242
 
            # assumed to have failed all checkers during downtime.
2243
 
            if client["enabled"]:
2244
 
                if datetime.datetime.utcnow() >= client["expires"]:
2245
 
                    if not client["last_checked_ok"]:
2246
 
                        logger.warning(
2247
 
                            "disabling client {0} - Client never "
2248
 
                            "performed a successfull checker"
2249
 
                            .format(client["name"]))
2250
 
                        client["enabled"] = False
2251
 
                    elif client["last_checker_status"] != 0:
2252
 
                        logger.warning(
2253
 
                            "disabling client {0} - Client "
2254
 
                            "last checker failed with error code {1}"
2255
 
                            .format(client["name"],
2256
 
                                    client["last_checker_status"]))
2257
 
                        client["enabled"] = False
2258
 
                    else:
2259
 
                        client["expires"] = (datetime.datetime
2260
 
                                             .utcnow()
2261
 
                                             + client["timeout"])
2262
 
                    
 
1884
        client_class = functools.partial(ClientDBus, bus = bus)
 
1885
    def client_config_items(config, section):
 
1886
        special_settings = {
 
1887
            "approved_by_default":
 
1888
                lambda: config.getboolean(section,
 
1889
                                          "approved_by_default"),
 
1890
            }
 
1891
        for name, value in config.items(section):
2263
1892
            try:
2264
 
                client["secret"] = (
2265
 
                    pgp.decrypt(client["encrypted_secret"],
2266
 
                                client_settings[client_name]
2267
 
                                ["secret"]))
2268
 
            except PGPError:
2269
 
                # If decryption fails, we use secret from new settings
2270
 
                logger.debug("Failed to decrypt {0} old secret"
2271
 
                             .format(client_name))
2272
 
                client["secret"] = (
2273
 
                    client_settings[client_name]["secret"])
2274
 
 
2275
 
    
2276
 
    # Add/remove clients based on new changes made to config
2277
 
    for client_name in set(old_client_settings) - set(client_settings):
2278
 
        del clients_data[client_name]
2279
 
    for client_name in set(client_settings) - set(old_client_settings):
2280
 
        clients_data[client_name] = client_settings[client_name]
2281
 
 
2282
 
    # Create clients all clients
2283
 
    for client_name, client in clients_data.iteritems():
2284
 
        tcp_server.clients[client_name] = client_class(
2285
 
            name = client_name, settings = client)
2286
 
    
 
1893
                yield (name, special_settings[name]())
 
1894
            except KeyError:
 
1895
                yield (name, value)
 
1896
    
 
1897
    tcp_server.clients.update(set(
 
1898
            client_class(name = section,
 
1899
                         config= dict(client_config_items(
 
1900
                        client_config, section)))
 
1901
            for section in client_config.sections()))
2287
1902
    if not tcp_server.clients:
2288
1903
        logger.warning("No clients defined")
2289
1904
        
2300
1915
            # "pidfile" was never created
2301
1916
            pass
2302
1917
        del pidfilename
 
1918
        
2303
1919
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2304
 
    
 
1920
 
2305
1921
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2306
1922
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2307
1923
    
2310
1926
            """A D-Bus proxy object"""
2311
1927
            def __init__(self):
2312
1928
                dbus.service.Object.__init__(self, bus, "/")
2313
 
            _interface = "se.recompile.Mandos"
 
1929
            _interface = "se.bsnet.fukt.Mandos"
2314
1930
            
2315
1931
            @dbus.service.signal(_interface, signature="o")
2316
1932
            def ClientAdded(self, objpath):
2331
1947
            def GetAllClients(self):
2332
1948
                "D-Bus method"
2333
1949
                return dbus.Array(c.dbus_object_path
2334
 
                                  for c in
2335
 
                                  tcp_server.clients.itervalues())
 
1950
                                  for c in tcp_server.clients)
2336
1951
            
2337
1952
            @dbus.service.method(_interface,
2338
1953
                                 out_signature="a{oa{sv}}")
2340
1955
                "D-Bus method"
2341
1956
                return dbus.Dictionary(
2342
1957
                    ((c.dbus_object_path, c.GetAll(""))
2343
 
                     for c in tcp_server.clients.itervalues()),
 
1958
                     for c in tcp_server.clients),
2344
1959
                    signature="oa{sv}")
2345
1960
            
2346
1961
            @dbus.service.method(_interface, in_signature="o")
2347
1962
            def RemoveClient(self, object_path):
2348
1963
                "D-Bus method"
2349
 
                for c in tcp_server.clients.itervalues():
 
1964
                for c in tcp_server.clients:
2350
1965
                    if c.dbus_object_path == object_path:
2351
 
                        del tcp_server.clients[c.name]
 
1966
                        tcp_server.clients.remove(c)
2352
1967
                        c.remove_from_connection()
2353
1968
                        # Don't signal anything except ClientRemoved
2354
1969
                        c.disable(quiet=True)
2359
1974
            
2360
1975
            del _interface
2361
1976
        
2362
 
        class MandosDBusServiceTransitional(MandosDBusService):
2363
 
            __metaclass__ = AlternateDBusNamesMetaclass
2364
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1977
        mandos_dbus_service = MandosDBusService()
2365
1978
    
2366
1979
    def cleanup():
2367
1980
        "Cleanup function; run on exit"
2368
1981
        service.cleanup()
2369
1982
        
2370
 
        multiprocessing.active_children()
2371
 
        if not (tcp_server.clients or client_settings):
2372
 
            return
2373
 
        
2374
 
        # Store client before exiting. Secrets are encrypted with key
2375
 
        # based on what config file has. If config file is
2376
 
        # removed/edited, old secret will thus be unrecovable.
2377
 
        clients = {}
2378
 
        with PGPEngine() as pgp:
2379
 
            for client in tcp_server.clients.itervalues():
2380
 
                key = client_settings[client.name]["secret"]
2381
 
                client.encrypted_secret = pgp.encrypt(client.secret,
2382
 
                                                      key)
2383
 
                client_dict = {}
2384
 
                
2385
 
                # A list of attributes that can not be pickled
2386
 
                # + secret.
2387
 
                exclude = set(("bus", "changedstate", "secret",
2388
 
                               "checker"))
2389
 
                for name, typ in (inspect.getmembers
2390
 
                                  (dbus.service.Object)):
2391
 
                    exclude.add(name)
2392
 
                
2393
 
                client_dict["encrypted_secret"] = (client
2394
 
                                                   .encrypted_secret)
2395
 
                for attr in client.client_structure:
2396
 
                    if attr not in exclude:
2397
 
                        client_dict[attr] = getattr(client, attr)
2398
 
                
2399
 
                clients[client.name] = client_dict
2400
 
                del client_settings[client.name]["secret"]
2401
 
        
2402
 
        try:
2403
 
            with os.fdopen(os.open(stored_state_path,
2404
 
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2405
 
                                   0600), "wb") as stored_state:
2406
 
                pickle.dump((clients, client_settings), stored_state)
2407
 
        except (IOError, OSError) as e:
2408
 
            logger.warning("Could not save persistent state: {0}"
2409
 
                           .format(e))
2410
 
            if e.errno not in (errno.ENOENT, errno.EACCES):
2411
 
                raise
2412
 
        
2413
 
        # Delete all clients, and settings from config
2414
1983
        while tcp_server.clients:
2415
 
            name, client = tcp_server.clients.popitem()
 
1984
            client = tcp_server.clients.pop()
2416
1985
            if use_dbus:
2417
1986
                client.remove_from_connection()
 
1987
            client.disable_hook = None
2418
1988
            # Don't signal anything except ClientRemoved
2419
1989
            client.disable(quiet=True)
2420
1990
            if use_dbus:
2421
1991
                # Emit D-Bus signal
2422
 
                mandos_dbus_service.ClientRemoved(client
2423
 
                                                  .dbus_object_path,
 
1992
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2424
1993
                                                  client.name)
2425
 
        client_settings.clear()
2426
1994
    
2427
1995
    atexit.register(cleanup)
2428
1996
    
2429
 
    for client in tcp_server.clients.itervalues():
 
1997
    for client in tcp_server.clients:
2430
1998
        if use_dbus:
2431
1999
            # Emit D-Bus signal
2432
2000
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2433
 
        # Need to initiate checking of clients
2434
 
        if client.enabled:
2435
 
            client.init_checker()
 
2001
        client.enable()
2436
2002
    
2437
2003
    tcp_server.enable()
2438
2004
    tcp_server.server_activate()
2453
2019
        # From the Avahi example code
2454
2020
        try:
2455
2021
            service.activate()
2456
 
        except dbus.exceptions.DBusException as error:
 
2022
        except dbus.exceptions.DBusException, error:
2457
2023
            logger.critical("DBusException: %s", error)
2458
2024
            cleanup()
2459
2025
            sys.exit(1)
2466
2032
        
2467
2033
        logger.debug("Starting main loop")
2468
2034
        main_loop.run()
2469
 
    except AvahiError as error:
 
2035
    except AvahiError, error:
2470
2036
        logger.critical("AvahiError: %s", error)
2471
2037
        cleanup()
2472
2038
        sys.exit(1)