/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2012-06-17 22:26:40 UTC
  • mfrom: (301.1.1 release)
  • Revision ID: teddy@recompile.se-20120617222640-49scfn0husnrr5bi
Tags: version-1.6.0-1
* Makefile (version): Changed to "1.6.0".
* NEWS (Version 1.6.0): New entry.
* debian/changelog (1.6.0-1): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python2.7
 
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2015 Teddy Hogeborn
15
 
# Copyright © 2008-2015 Björn Påhlsson
 
14
# Copyright © 2008-2012 Teddy Hogeborn
 
15
# Copyright © 2008-2012 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
68
68
import binascii
69
69
import tempfile
70
70
import itertools
71
 
import collections
72
71
 
73
72
import dbus
74
73
import dbus.service
79
78
import ctypes.util
80
79
import xml.dom.minidom
81
80
import inspect
 
81
import GnuPGInterface
82
82
 
83
83
try:
84
84
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
88
88
    except ImportError:
89
89
        SO_BINDTODEVICE = None
90
90
 
91
 
if sys.version_info.major == 2:
92
 
    str = unicode
93
 
 
94
 
version = "1.6.9"
 
91
version = "1.6.0"
95
92
stored_state_file = "clients.pickle"
96
93
 
97
94
logger = logging.getLogger()
98
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
99
98
 
100
99
try:
101
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
102
 
        ctypes.util.find_library("c")).if_nametoindex
 
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
101
                      (ctypes.util.find_library("c"))
 
102
                      .if_nametoindex)
103
103
except (OSError, AttributeError):
104
 
    
105
104
    def if_nametoindex(interface):
106
105
        "Get an interface index the hard way, i.e. using fcntl()"
107
106
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
108
107
        with contextlib.closing(socket.socket()) as s:
109
108
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
 
                                struct.pack(b"16s16x", interface))
111
 
        interface_index = struct.unpack("I", ifreq[16:20])[0]
 
109
                                struct.pack(str("16s16x"),
 
110
                                            interface))
 
111
        interface_index = struct.unpack(str("I"),
 
112
                                        ifreq[16:20])[0]
112
113
        return interface_index
113
114
 
114
115
 
115
116
def initlogger(debug, level=logging.WARNING):
116
117
    """init logger and add loglevel"""
117
118
    
118
 
    global syslogger
119
 
    syslogger = (logging.handlers.SysLogHandler(
120
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
 
        address = "/dev/log"))
122
119
    syslogger.setFormatter(logging.Formatter
123
120
                           ('Mandos [%(process)d]: %(levelname)s:'
124
121
                            ' %(message)s'))
141
138
 
142
139
class PGPEngine(object):
143
140
    """A simple class for OpenPGP symmetric encryption & decryption"""
144
 
    
145
141
    def __init__(self):
 
142
        self.gnupg = GnuPGInterface.GnuPG()
146
143
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
147
 
        self.gnupgargs = ['--batch',
148
 
                          '--home', self.tempdir,
149
 
                          '--force-mdc',
150
 
                          '--quiet',
151
 
                          '--no-use-agent']
 
144
        self.gnupg = GnuPGInterface.GnuPG()
 
145
        self.gnupg.options.meta_interactive = False
 
146
        self.gnupg.options.homedir = self.tempdir
 
147
        self.gnupg.options.extra_args.extend(['--force-mdc',
 
148
                                              '--quiet',
 
149
                                              '--no-use-agent'])
152
150
    
153
151
    def __enter__(self):
154
152
        return self
176
174
    def password_encode(self, password):
177
175
        # Passphrase can not be empty and can not contain newlines or
178
176
        # NUL bytes.  So we prefix it and hex encode it.
179
 
        encoded = b"mandos" + binascii.hexlify(password)
180
 
        if len(encoded) > 2048:
181
 
            # GnuPG can't handle long passwords, so encode differently
182
 
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
183
 
                       .replace(b"\n", b"\\n")
184
 
                       .replace(b"\0", b"\\x00"))
185
 
        return encoded
 
177
        return b"mandos" + binascii.hexlify(password)
186
178
    
187
179
    def encrypt(self, data, password):
188
 
        passphrase = self.password_encode(password)
189
 
        with tempfile.NamedTemporaryFile(
190
 
                dir=self.tempdir) as passfile:
191
 
            passfile.write(passphrase)
192
 
            passfile.flush()
193
 
            proc = subprocess.Popen(['gpg', '--symmetric',
194
 
                                     '--passphrase-file',
195
 
                                     passfile.name]
196
 
                                    + self.gnupgargs,
197
 
                                    stdin = subprocess.PIPE,
198
 
                                    stdout = subprocess.PIPE,
199
 
                                    stderr = subprocess.PIPE)
200
 
            ciphertext, err = proc.communicate(input = data)
201
 
        if proc.returncode != 0:
202
 
            raise PGPError(err)
 
180
        self.gnupg.passphrase = self.password_encode(password)
 
181
        with open(os.devnull, "w") as devnull:
 
182
            try:
 
183
                proc = self.gnupg.run(['--symmetric'],
 
184
                                      create_fhs=['stdin', 'stdout'],
 
185
                                      attach_fhs={'stderr': devnull})
 
186
                with contextlib.closing(proc.handles['stdin']) as f:
 
187
                    f.write(data)
 
188
                with contextlib.closing(proc.handles['stdout']) as f:
 
189
                    ciphertext = f.read()
 
190
                proc.wait()
 
191
            except IOError as e:
 
192
                raise PGPError(e)
 
193
        self.gnupg.passphrase = None
203
194
        return ciphertext
204
195
    
205
196
    def decrypt(self, data, password):
206
 
        passphrase = self.password_encode(password)
207
 
        with tempfile.NamedTemporaryFile(
208
 
                dir = self.tempdir) as passfile:
209
 
            passfile.write(passphrase)
210
 
            passfile.flush()
211
 
            proc = subprocess.Popen(['gpg', '--decrypt',
212
 
                                     '--passphrase-file',
213
 
                                     passfile.name]
214
 
                                    + self.gnupgargs,
215
 
                                    stdin = subprocess.PIPE,
216
 
                                    stdout = subprocess.PIPE,
217
 
                                    stderr = subprocess.PIPE)
218
 
            decrypted_plaintext, err = proc.communicate(input = data)
219
 
        if proc.returncode != 0:
220
 
            raise PGPError(err)
 
197
        self.gnupg.passphrase = self.password_encode(password)
 
198
        with open(os.devnull, "w") as devnull:
 
199
            try:
 
200
                proc = self.gnupg.run(['--decrypt'],
 
201
                                      create_fhs=['stdin', 'stdout'],
 
202
                                      attach_fhs={'stderr': devnull})
 
203
                with contextlib.closing(proc.handles['stdin']) as f:
 
204
                    f.write(data)
 
205
                with contextlib.closing(proc.handles['stdout']) as f:
 
206
                    decrypted_plaintext = f.read()
 
207
                proc.wait()
 
208
            except IOError as e:
 
209
                raise PGPError(e)
 
210
        self.gnupg.passphrase = None
221
211
        return decrypted_plaintext
222
212
 
223
213
 
224
214
class AvahiError(Exception):
225
215
    def __init__(self, value, *args, **kwargs):
226
216
        self.value = value
227
 
        return super(AvahiError, self).__init__(value, *args,
228
 
                                                **kwargs)
229
 
 
 
217
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
218
    def __unicode__(self):
 
219
        return unicode(repr(self.value))
230
220
 
231
221
class AvahiServiceError(AvahiError):
232
222
    pass
233
223
 
234
 
 
235
224
class AvahiGroupError(AvahiError):
236
225
    pass
237
226
 
244
233
               Used to optionally bind to the specified interface.
245
234
    name: string; Example: 'Mandos'
246
235
    type: string; Example: '_mandos._tcp'.
247
 
     See <https://www.iana.org/assignments/service-names-port-numbers>
 
236
                  See <http://www.dns-sd.org/ServiceTypes.html>
248
237
    port: integer; what port to announce
249
238
    TXT: list of strings; TXT record for the service
250
239
    domain: string; Domain to publish on, default to .local if empty.
257
246
    bus: dbus.SystemBus()
258
247
    """
259
248
    
260
 
    def __init__(self,
261
 
                 interface = avahi.IF_UNSPEC,
262
 
                 name = None,
263
 
                 servicetype = None,
264
 
                 port = None,
265
 
                 TXT = None,
266
 
                 domain = "",
267
 
                 host = "",
268
 
                 max_renames = 32768,
269
 
                 protocol = avahi.PROTO_UNSPEC,
270
 
                 bus = None):
 
249
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
250
                 servicetype = None, port = None, TXT = None,
 
251
                 domain = "", host = "", max_renames = 32768,
 
252
                 protocol = avahi.PROTO_UNSPEC, bus = None):
271
253
        self.interface = interface
272
254
        self.name = name
273
255
        self.type = servicetype
283
265
        self.bus = bus
284
266
        self.entry_group_state_changed_match = None
285
267
    
286
 
    def rename(self, remove=True):
 
268
    def rename(self):
287
269
        """Derived from the Avahi example code"""
288
270
        if self.rename_count >= self.max_renames:
289
271
            logger.critical("No suitable Zeroconf service name found"
290
272
                            " after %i retries, exiting.",
291
273
                            self.rename_count)
292
274
            raise AvahiServiceError("Too many renames")
293
 
        self.name = str(
294
 
            self.server.GetAlternativeServiceName(self.name))
295
 
        self.rename_count += 1
 
275
        self.name = unicode(self.server
 
276
                            .GetAlternativeServiceName(self.name))
296
277
        logger.info("Changing Zeroconf service name to %r ...",
297
278
                    self.name)
298
 
        if remove:
299
 
            self.remove()
 
279
        self.remove()
300
280
        try:
301
281
            self.add()
302
282
        except dbus.exceptions.DBusException as error:
303
 
            if (error.get_dbus_name()
304
 
                == "org.freedesktop.Avahi.CollisionError"):
305
 
                logger.info("Local Zeroconf service name collision.")
306
 
                return self.rename(remove=False)
307
 
            else:
308
 
                logger.critical("D-Bus Exception", exc_info=error)
309
 
                self.cleanup()
310
 
                os._exit(1)
 
283
            logger.critical("D-Bus Exception", exc_info=error)
 
284
            self.cleanup()
 
285
            os._exit(1)
 
286
        self.rename_count += 1
311
287
    
312
288
    def remove(self):
313
289
        """Derived from the Avahi example code"""
351
327
            self.rename()
352
328
        elif state == avahi.ENTRY_GROUP_FAILURE:
353
329
            logger.critical("Avahi: Error in group state changed %s",
354
 
                            str(error))
355
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
330
                            unicode(error))
 
331
            raise AvahiGroupError("State changed: {0!s}"
 
332
                                  .format(error))
356
333
    
357
334
    def cleanup(self):
358
335
        """Derived from the Avahi example code"""
368
345
    def server_state_changed(self, state, error=None):
369
346
        """Derived from the Avahi example code"""
370
347
        logger.debug("Avahi server state change: %i", state)
371
 
        bad_states = {
372
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
373
 
            avahi.SERVER_REGISTERING: None,
374
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
375
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
376
 
        }
 
348
        bad_states = { avahi.SERVER_INVALID:
 
349
                           "Zeroconf server invalid",
 
350
                       avahi.SERVER_REGISTERING: None,
 
351
                       avahi.SERVER_COLLISION:
 
352
                           "Zeroconf server name collision",
 
353
                       avahi.SERVER_FAILURE:
 
354
                           "Zeroconf server failure" }
377
355
        if state in bad_states:
378
356
            if bad_states[state] is not None:
379
357
                if error is None:
398
376
                                    follow_name_owner_changes=True),
399
377
                avahi.DBUS_INTERFACE_SERVER)
400
378
        self.server.connect_to_signal("StateChanged",
401
 
                                      self.server_state_changed)
 
379
                                 self.server_state_changed)
402
380
        self.server_state_changed(self.server.GetState())
403
381
 
404
382
 
405
383
class AvahiServiceToSyslog(AvahiService):
406
 
    def rename(self, *args, **kwargs):
 
384
    def rename(self):
407
385
        """Add the new name to the syslog messages"""
408
 
        ret = AvahiService.rename(self, *args, **kwargs)
409
 
        syslogger.setFormatter(logging.Formatter(
410
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
411
 
            .format(self.name)))
 
386
        ret = AvahiService.rename(self)
 
387
        syslogger.setFormatter(logging.Formatter
 
388
                               ('Mandos ({0}) [%(process)d]:'
 
389
                                ' %(levelname)s: %(message)s'
 
390
                                .format(self.name)))
412
391
        return ret
413
392
 
414
393
 
 
394
def timedelta_to_milliseconds(td):
 
395
    "Convert a datetime.timedelta() to milliseconds"
 
396
    return ((td.days * 24 * 60 * 60 * 1000)
 
397
            + (td.seconds * 1000)
 
398
            + (td.microseconds // 1000))
 
399
 
 
400
 
415
401
class Client(object):
416
402
    """A representation of a client host served by this server.
417
403
    
453
439
    runtime_expansions: Allowed attributes for runtime expansion.
454
440
    expires:    datetime.datetime(); time (UTC) when a client will be
455
441
                disabled, or None
456
 
    server_settings: The server_settings dict from main()
457
442
    """
458
443
    
459
444
    runtime_expansions = ("approval_delay", "approval_duration",
461
446
                          "fingerprint", "host", "interval",
462
447
                          "last_approval_request", "last_checked_ok",
463
448
                          "last_enabled", "name", "timeout")
464
 
    client_defaults = {
465
 
        "timeout": "PT5M",
466
 
        "extended_timeout": "PT15M",
467
 
        "interval": "PT2M",
468
 
        "checker": "fping -q -- %%(host)s",
469
 
        "host": "",
470
 
        "approval_delay": "PT0S",
471
 
        "approval_duration": "PT1S",
472
 
        "approved_by_default": "True",
473
 
        "enabled": "True",
474
 
    }
 
449
    client_defaults = { "timeout": "5m",
 
450
                        "extended_timeout": "15m",
 
451
                        "interval": "2m",
 
452
                        "checker": "fping -q -- %%(host)s",
 
453
                        "host": "",
 
454
                        "approval_delay": "0s",
 
455
                        "approval_duration": "1s",
 
456
                        "approved_by_default": "True",
 
457
                        "enabled": "True",
 
458
                        }
 
459
    
 
460
    def timeout_milliseconds(self):
 
461
        "Return the 'timeout' attribute in milliseconds"
 
462
        return timedelta_to_milliseconds(self.timeout)
 
463
    
 
464
    def extended_timeout_milliseconds(self):
 
465
        "Return the 'extended_timeout' attribute in milliseconds"
 
466
        return timedelta_to_milliseconds(self.extended_timeout)
 
467
    
 
468
    def interval_milliseconds(self):
 
469
        "Return the 'interval' attribute in milliseconds"
 
470
        return timedelta_to_milliseconds(self.interval)
 
471
    
 
472
    def approval_delay_milliseconds(self):
 
473
        return timedelta_to_milliseconds(self.approval_delay)
475
474
    
476
475
    @staticmethod
477
476
    def config_parser(config):
493
492
            client["enabled"] = config.getboolean(client_name,
494
493
                                                  "enabled")
495
494
            
496
 
            # Uppercase and remove spaces from fingerprint for later
497
 
            # comparison purposes with return value from the
498
 
            # fingerprint() function
499
495
            client["fingerprint"] = (section["fingerprint"].upper()
500
496
                                     .replace(" ", ""))
501
497
            if "secret" in section:
506
502
                          "rb") as secfile:
507
503
                    client["secret"] = secfile.read()
508
504
            else:
509
 
                raise TypeError("No secret or secfile for section {}"
 
505
                raise TypeError("No secret or secfile for section {0}"
510
506
                                .format(section))
511
507
            client["timeout"] = string_to_delta(section["timeout"])
512
508
            client["extended_timeout"] = string_to_delta(
523
519
        
524
520
        return settings
525
521
    
526
 
    def __init__(self, settings, name = None, server_settings=None):
 
522
    def __init__(self, settings, name = None):
527
523
        self.name = name
528
 
        if server_settings is None:
529
 
            server_settings = {}
530
 
        self.server_settings = server_settings
531
524
        # adding all client settings
532
 
        for setting, value in settings.items():
 
525
        for setting, value in settings.iteritems():
533
526
            setattr(self, setting, value)
534
527
        
535
528
        if self.enabled:
543
536
            self.expires = None
544
537
        
545
538
        logger.debug("Creating client %r", self.name)
 
539
        # Uppercase and remove spaces from fingerprint for later
 
540
        # comparison purposes with return value from the fingerprint()
 
541
        # function
546
542
        logger.debug("  Fingerprint: %s", self.fingerprint)
547
543
        self.created = settings.get("created",
548
544
                                    datetime.datetime.utcnow())
555
551
        self.current_checker_command = None
556
552
        self.approved = None
557
553
        self.approvals_pending = 0
558
 
        self.changedstate = multiprocessing_manager.Condition(
559
 
            multiprocessing_manager.Lock())
560
 
        self.client_structure = [attr
561
 
                                 for attr in self.__dict__.iterkeys()
 
554
        self.changedstate = (multiprocessing_manager
 
555
                             .Condition(multiprocessing_manager
 
556
                                        .Lock()))
 
557
        self.client_structure = [attr for attr in
 
558
                                 self.__dict__.iterkeys()
562
559
                                 if not attr.startswith("_")]
563
560
        self.client_structure.append("client_structure")
564
561
        
565
 
        for name, t in inspect.getmembers(
566
 
                type(self), lambda obj: isinstance(obj, property)):
 
562
        for name, t in inspect.getmembers(type(self),
 
563
                                          lambda obj:
 
564
                                              isinstance(obj,
 
565
                                                         property)):
567
566
            if not name.startswith("_"):
568
567
                self.client_structure.append(name)
569
568
    
611
610
        # and every interval from then on.
612
611
        if self.checker_initiator_tag is not None:
613
612
            gobject.source_remove(self.checker_initiator_tag)
614
 
        self.checker_initiator_tag = gobject.timeout_add(
615
 
            int(self.interval.total_seconds() * 1000),
616
 
            self.start_checker)
 
613
        self.checker_initiator_tag = (gobject.timeout_add
 
614
                                      (self.interval_milliseconds(),
 
615
                                       self.start_checker))
617
616
        # Schedule a disable() when 'timeout' has passed
618
617
        if self.disable_initiator_tag is not None:
619
618
            gobject.source_remove(self.disable_initiator_tag)
620
 
        self.disable_initiator_tag = gobject.timeout_add(
621
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
619
        self.disable_initiator_tag = (gobject.timeout_add
 
620
                                   (self.timeout_milliseconds(),
 
621
                                    self.disable))
622
622
        # Also start a new checker *right now*.
623
623
        self.start_checker()
624
624
    
633
633
                            vars(self))
634
634
                self.checked_ok()
635
635
            else:
636
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
637
638
        else:
638
639
            self.last_checker_status = -1
639
640
            logger.warning("Checker for %(name)s crashed?",
653
654
            gobject.source_remove(self.disable_initiator_tag)
654
655
            self.disable_initiator_tag = None
655
656
        if getattr(self, "enabled", False):
656
 
            self.disable_initiator_tag = gobject.timeout_add(
657
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (timedelta_to_milliseconds
 
659
                                           (timeout), self.disable))
658
660
            self.expires = datetime.datetime.utcnow() + timeout
659
661
    
660
662
    def need_approval(self):
677
679
        # If a checker exists, make sure it is not a zombie
678
680
        try:
679
681
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
680
 
        except AttributeError:
681
 
            pass
682
 
        except OSError as error:
683
 
            if error.errno != errno.ECHILD:
684
 
                raise
 
682
        except (AttributeError, OSError) as error:
 
683
            if (isinstance(error, OSError)
 
684
                and error.errno != errno.ECHILD):
 
685
                raise error
685
686
        else:
686
687
            if pid:
687
688
                logger.warning("Checker was a zombie")
691
692
        # Start a new checker if needed
692
693
        if self.checker is None:
693
694
            # Escape attributes for the shell
694
 
            escaped_attrs = {
695
 
                attr: re.escape(str(getattr(self, attr)))
696
 
                for attr in self.runtime_expansions }
 
695
            escaped_attrs = dict(
 
696
                (attr, re.escape(unicode(getattr(self, attr))))
 
697
                for attr in
 
698
                self.runtime_expansions)
697
699
            try:
698
700
                command = self.checker_command % escaped_attrs
699
701
            except TypeError as error:
700
702
                logger.error('Could not format string "%s"',
701
 
                             self.checker_command,
702
 
                             exc_info=error)
703
 
                return True     # Try again later
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
704
705
            self.current_checker_command = command
705
706
            try:
706
 
                logger.info("Starting checker %r for %s", command,
707
 
                            self.name)
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
708
709
                # We don't need to redirect stdout and stderr, since
709
710
                # in normal mode, that is already done by daemon(),
710
711
                # and in debug mode we don't want to.  (Stdin is
711
712
                # always replaced by /dev/null.)
712
 
                # The exception is when not debugging but nevertheless
713
 
                # running in the foreground; use the previously
714
 
                # created wnull.
715
 
                popen_args = {}
716
 
                if (not self.server_settings["debug"]
717
 
                    and self.server_settings["foreground"]):
718
 
                    popen_args.update({"stdout": wnull,
719
 
                                       "stderr": wnull })
720
713
                self.checker = subprocess.Popen(command,
721
714
                                                close_fds=True,
722
 
                                                shell=True,
723
 
                                                cwd="/",
724
 
                                                **popen_args)
 
715
                                                shell=True, cwd="/")
725
716
            except OSError as error:
726
717
                logger.error("Failed to start subprocess",
727
718
                             exc_info=error)
728
 
                return True
729
 
            self.checker_callback_tag = gobject.child_watch_add(
730
 
                self.checker.pid, self.checker_callback, data=command)
 
719
            self.checker_callback_tag = (gobject.child_watch_add
 
720
                                         (self.checker.pid,
 
721
                                          self.checker_callback,
 
722
                                          data=command))
731
723
            # The checker may have completed before the gobject
732
724
            # watch was added.  Check for this.
733
 
            try:
734
 
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
735
 
            except OSError as error:
736
 
                if error.errno == errno.ECHILD:
737
 
                    # This should never happen
738
 
                    logger.error("Child process vanished",
739
 
                                 exc_info=error)
740
 
                    return True
741
 
                raise
 
725
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
742
726
            if pid:
743
727
                gobject.source_remove(self.checker_callback_tag)
744
728
                self.checker_callback(pid, status, command)
764
748
        self.checker = None
765
749
 
766
750
 
767
 
def dbus_service_property(dbus_interface,
768
 
                          signature="v",
769
 
                          access="readwrite",
770
 
                          byte_arrays=False):
 
751
def dbus_service_property(dbus_interface, signature="v",
 
752
                          access="readwrite", byte_arrays=False):
771
753
    """Decorators for marking methods of a DBusObjectWithProperties to
772
754
    become properties on the D-Bus.
773
755
    
782
764
    # "Set" method, so we fail early here:
783
765
    if byte_arrays and signature != "ay":
784
766
        raise ValueError("Byte arrays not supported for non-'ay'"
785
 
                         " signature {!r}".format(signature))
786
 
    
 
767
                         " signature {0!r}".format(signature))
787
768
    def decorator(func):
788
769
        func._dbus_is_property = True
789
770
        func._dbus_interface = dbus_interface
794
775
            func._dbus_name = func._dbus_name[:-14]
795
776
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
796
777
        return func
797
 
    
798
778
    return decorator
799
779
 
800
780
 
809
789
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
810
790
                    "false"}
811
791
    """
812
 
    
813
792
    def decorator(func):
814
793
        func._dbus_is_interface = True
815
794
        func._dbus_interface = dbus_interface
816
795
        func._dbus_name = dbus_interface
817
796
        return func
818
 
    
819
797
    return decorator
820
798
 
821
799
 
823
801
    """Decorator to annotate D-Bus methods, signals or properties
824
802
    Usage:
825
803
    
826
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
827
 
                       "org.freedesktop.DBus.Property."
828
 
                       "EmitsChangedSignal": "false"})
829
804
    @dbus_service_property("org.example.Interface", signature="b",
830
805
                           access="r")
 
806
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
807
                        "org.freedesktop.DBus.Property."
 
808
                        "EmitsChangedSignal": "false"})
831
809
    def Property_dbus_property(self):
832
810
        return dbus.Boolean(False)
833
811
    """
834
 
    
835
812
    def decorator(func):
836
813
        func._dbus_annotations = annotations
837
814
        return func
838
 
    
839
815
    return decorator
840
816
 
841
817
 
842
818
class DBusPropertyException(dbus.exceptions.DBusException):
843
819
    """A base class for D-Bus property-related exceptions
844
820
    """
845
 
    pass
 
821
    def __unicode__(self):
 
822
        return unicode(str(self))
846
823
 
847
824
 
848
825
class DBusPropertyAccessException(DBusPropertyException):
872
849
        If called like _is_dbus_thing("method") it returns a function
873
850
        suitable for use as predicate to inspect.getmembers().
874
851
        """
875
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
852
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
876
853
                                   False)
877
854
    
878
855
    def _get_all_dbus_things(self, thing):
879
856
        """Returns a generator of (name, attribute) pairs
880
857
        """
881
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
858
        return ((getattr(athing.__get__(self), "_dbus_name",
 
859
                         name),
882
860
                 athing.__get__(self))
883
861
                for cls in self.__class__.__mro__
884
862
                for name, athing in
885
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
863
                inspect.getmembers(cls,
 
864
                                   self._is_dbus_thing(thing)))
886
865
    
887
866
    def _get_dbus_property(self, interface_name, property_name):
888
867
        """Returns a bound method if one exists which is a D-Bus
889
868
        property with the specified name and interface.
890
869
        """
891
 
        for cls in self.__class__.__mro__:
892
 
            for name, value in inspect.getmembers(
893
 
                    cls, self._is_dbus_thing("property")):
 
870
        for cls in  self.__class__.__mro__:
 
871
            for name, value in (inspect.getmembers
 
872
                                (cls,
 
873
                                 self._is_dbus_thing("property"))):
894
874
                if (value._dbus_name == property_name
895
875
                    and value._dbus_interface == interface_name):
896
876
                    return value.__get__(self)
897
877
        
898
878
        # No such property
899
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
900
 
            self.dbus_object_path, interface_name, property_name))
 
879
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
880
                                   + interface_name + "."
 
881
                                   + property_name)
901
882
    
902
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
903
 
                         in_signature="ss",
 
883
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
884
                         out_signature="v")
905
885
    def Get(self, interface_name, property_name):
906
886
        """Standard D-Bus property Get() method, see D-Bus standard.
924
904
            # The byte_arrays option is not supported yet on
925
905
            # signatures other than "ay".
926
906
            if prop._dbus_signature != "ay":
927
 
                raise ValueError("Byte arrays not supported for non-"
928
 
                                 "'ay' signature {!r}"
929
 
                                 .format(prop._dbus_signature))
 
907
                raise ValueError
930
908
            value = dbus.ByteArray(b''.join(chr(byte)
931
909
                                            for byte in value))
932
910
        prop(value)
933
911
    
934
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
935
 
                         in_signature="s",
 
912
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
936
913
                         out_signature="a{sv}")
937
914
    def GetAll(self, interface_name):
938
915
        """Standard D-Bus property GetAll() method, see D-Bus
953
930
            if not hasattr(value, "variant_level"):
954
931
                properties[name] = value
955
932
                continue
956
 
            properties[name] = type(value)(
957
 
                value, variant_level = value.variant_level + 1)
 
933
            properties[name] = type(value)(value, variant_level=
 
934
                                           value.variant_level+1)
958
935
        return dbus.Dictionary(properties, signature="sv")
959
936
    
960
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
961
 
    def PropertiesChanged(self, interface_name, changed_properties,
962
 
                          invalidated_properties):
963
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
964
 
        standard.
965
 
        """
966
 
        pass
967
 
    
968
937
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
969
938
                         out_signature="s",
970
939
                         path_keyword='object_path',
978
947
                                                   connection)
979
948
        try:
980
949
            document = xml.dom.minidom.parseString(xmlstring)
981
 
            
982
950
            def make_tag(document, name, prop):
983
951
                e = document.createElement("property")
984
952
                e.setAttribute("name", name)
985
953
                e.setAttribute("type", prop._dbus_signature)
986
954
                e.setAttribute("access", prop._dbus_access)
987
955
                return e
988
 
            
989
956
            for if_tag in document.getElementsByTagName("interface"):
990
957
                # Add property tags
991
958
                for tag in (make_tag(document, name, prop)
1003
970
                            if (name == tag.getAttribute("name")
1004
971
                                and prop._dbus_interface
1005
972
                                == if_tag.getAttribute("name")):
1006
 
                                annots.update(getattr(
1007
 
                                    prop, "_dbus_annotations", {}))
1008
 
                        for name, value in annots.items():
 
973
                                annots.update(getattr
 
974
                                              (prop,
 
975
                                               "_dbus_annotations",
 
976
                                               {}))
 
977
                        for name, value in annots.iteritems():
1009
978
                            ann_tag = document.createElement(
1010
979
                                "annotation")
1011
980
                            ann_tag.setAttribute("name", name)
1014
983
                # Add interface annotation tags
1015
984
                for annotation, value in dict(
1016
985
                    itertools.chain.from_iterable(
1017
 
                        annotations().items()
1018
 
                        for name, annotations
1019
 
                        in self._get_all_dbus_things("interface")
 
986
                        annotations().iteritems()
 
987
                        for name, annotations in
 
988
                        self._get_all_dbus_things("interface")
1020
989
                        if name == if_tag.getAttribute("name")
1021
 
                        )).items():
 
990
                        )).iteritems():
1022
991
                    ann_tag = document.createElement("annotation")
1023
992
                    ann_tag.setAttribute("name", annotation)
1024
993
                    ann_tag.setAttribute("value", value)
1051
1020
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1052
1021
    if dt is None:
1053
1022
        return dbus.String("", variant_level = variant_level)
1054
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1023
    return dbus.String(dt.isoformat(),
 
1024
                       variant_level=variant_level)
1055
1025
 
1056
1026
 
1057
1027
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1077
1047
    (from DBusObjectWithProperties) and interfaces (from the
1078
1048
    dbus_interface_annotations decorator).
1079
1049
    """
1080
 
    
1081
1050
    def wrapper(cls):
1082
1051
        for orig_interface_name, alt_interface_name in (
1083
 
                alt_interface_names.items()):
 
1052
            alt_interface_names.iteritems()):
1084
1053
            attr = {}
1085
1054
            interface_names = set()
1086
1055
            # Go though all attributes of the class
1088
1057
                # Ignore non-D-Bus attributes, and D-Bus attributes
1089
1058
                # with the wrong interface name
1090
1059
                if (not hasattr(attribute, "_dbus_interface")
1091
 
                    or not attribute._dbus_interface.startswith(
1092
 
                        orig_interface_name)):
 
1060
                    or not attribute._dbus_interface
 
1061
                    .startswith(orig_interface_name)):
1093
1062
                    continue
1094
1063
                # Create an alternate D-Bus interface name based on
1095
1064
                # the current name
1096
 
                alt_interface = attribute._dbus_interface.replace(
1097
 
                    orig_interface_name, alt_interface_name)
 
1065
                alt_interface = (attribute._dbus_interface
 
1066
                                 .replace(orig_interface_name,
 
1067
                                          alt_interface_name))
1098
1068
                interface_names.add(alt_interface)
1099
1069
                # Is this a D-Bus signal?
1100
1070
                if getattr(attribute, "_dbus_is_signal", False):
1101
 
                    # Extract the original non-method undecorated
1102
 
                    # function by black magic
 
1071
                    # Extract the original non-method function by
 
1072
                    # black magic
1103
1073
                    nonmethod_func = (dict(
1104
 
                        zip(attribute.func_code.co_freevars,
1105
 
                            attribute.__closure__))
1106
 
                                      ["func"].cell_contents)
 
1074
                            zip(attribute.func_code.co_freevars,
 
1075
                                attribute.__closure__))["func"]
 
1076
                                      .cell_contents)
1107
1077
                    # Create a new, but exactly alike, function
1108
1078
                    # object, and decorate it to be a new D-Bus signal
1109
1079
                    # with the alternate D-Bus interface name
1110
 
                    new_function = (dbus.service.signal(
1111
 
                        alt_interface, attribute._dbus_signature)
 
1080
                    new_function = (dbus.service.signal
 
1081
                                    (alt_interface,
 
1082
                                     attribute._dbus_signature)
1112
1083
                                    (types.FunctionType(
1113
 
                                        nonmethod_func.func_code,
1114
 
                                        nonmethod_func.func_globals,
1115
 
                                        nonmethod_func.func_name,
1116
 
                                        nonmethod_func.func_defaults,
1117
 
                                        nonmethod_func.func_closure)))
 
1084
                                nonmethod_func.func_code,
 
1085
                                nonmethod_func.func_globals,
 
1086
                                nonmethod_func.func_name,
 
1087
                                nonmethod_func.func_defaults,
 
1088
                                nonmethod_func.func_closure)))
1118
1089
                    # Copy annotations, if any
1119
1090
                    try:
1120
 
                        new_function._dbus_annotations = dict(
1121
 
                            attribute._dbus_annotations)
 
1091
                        new_function._dbus_annotations = (
 
1092
                            dict(attribute._dbus_annotations))
1122
1093
                    except AttributeError:
1123
1094
                        pass
1124
1095
                    # Define a creator of a function to call both the
1129
1100
                        """This function is a scope container to pass
1130
1101
                        func1 and func2 to the "call_both" function
1131
1102
                        outside of its arguments"""
1132
 
                        
1133
1103
                        def call_both(*args, **kwargs):
1134
1104
                            """This function will emit two D-Bus
1135
1105
                            signals by calling func1 and func2"""
1136
1106
                            func1(*args, **kwargs)
1137
1107
                            func2(*args, **kwargs)
1138
 
                        
1139
1108
                        return call_both
1140
1109
                    # Create the "call_both" function and add it to
1141
1110
                    # the class
1146
1115
                    # object.  Decorate it to be a new D-Bus method
1147
1116
                    # with the alternate D-Bus interface name.  Add it
1148
1117
                    # to the class.
1149
 
                    attr[attrname] = (
1150
 
                        dbus.service.method(
1151
 
                            alt_interface,
1152
 
                            attribute._dbus_in_signature,
1153
 
                            attribute._dbus_out_signature)
1154
 
                        (types.FunctionType(attribute.func_code,
1155
 
                                            attribute.func_globals,
1156
 
                                            attribute.func_name,
1157
 
                                            attribute.func_defaults,
1158
 
                                            attribute.func_closure)))
 
1118
                    attr[attrname] = (dbus.service.method
 
1119
                                      (alt_interface,
 
1120
                                       attribute._dbus_in_signature,
 
1121
                                       attribute._dbus_out_signature)
 
1122
                                      (types.FunctionType
 
1123
                                       (attribute.func_code,
 
1124
                                        attribute.func_globals,
 
1125
                                        attribute.func_name,
 
1126
                                        attribute.func_defaults,
 
1127
                                        attribute.func_closure)))
1159
1128
                    # Copy annotations, if any
1160
1129
                    try:
1161
 
                        attr[attrname]._dbus_annotations = dict(
1162
 
                            attribute._dbus_annotations)
 
1130
                        attr[attrname]._dbus_annotations = (
 
1131
                            dict(attribute._dbus_annotations))
1163
1132
                    except AttributeError:
1164
1133
                        pass
1165
1134
                # Is this a D-Bus property?
1168
1137
                    # object, and decorate it to be a new D-Bus
1169
1138
                    # property with the alternate D-Bus interface
1170
1139
                    # name.  Add it to the class.
1171
 
                    attr[attrname] = (dbus_service_property(
1172
 
                        alt_interface, attribute._dbus_signature,
1173
 
                        attribute._dbus_access,
1174
 
                        attribute._dbus_get_args_options
1175
 
                        ["byte_arrays"])
1176
 
                                      (types.FunctionType(
1177
 
                                          attribute.func_code,
1178
 
                                          attribute.func_globals,
1179
 
                                          attribute.func_name,
1180
 
                                          attribute.func_defaults,
1181
 
                                          attribute.func_closure)))
 
1140
                    attr[attrname] = (dbus_service_property
 
1141
                                      (alt_interface,
 
1142
                                       attribute._dbus_signature,
 
1143
                                       attribute._dbus_access,
 
1144
                                       attribute
 
1145
                                       ._dbus_get_args_options
 
1146
                                       ["byte_arrays"])
 
1147
                                      (types.FunctionType
 
1148
                                       (attribute.func_code,
 
1149
                                        attribute.func_globals,
 
1150
                                        attribute.func_name,
 
1151
                                        attribute.func_defaults,
 
1152
                                        attribute.func_closure)))
1182
1153
                    # Copy annotations, if any
1183
1154
                    try:
1184
 
                        attr[attrname]._dbus_annotations = dict(
1185
 
                            attribute._dbus_annotations)
 
1155
                        attr[attrname]._dbus_annotations = (
 
1156
                            dict(attribute._dbus_annotations))
1186
1157
                    except AttributeError:
1187
1158
                        pass
1188
1159
                # Is this a D-Bus interface?
1191
1162
                    # object.  Decorate it to be a new D-Bus interface
1192
1163
                    # with the alternate D-Bus interface name.  Add it
1193
1164
                    # to the class.
1194
 
                    attr[attrname] = (
1195
 
                        dbus_interface_annotations(alt_interface)
1196
 
                        (types.FunctionType(attribute.func_code,
1197
 
                                            attribute.func_globals,
1198
 
                                            attribute.func_name,
1199
 
                                            attribute.func_defaults,
1200
 
                                            attribute.func_closure)))
 
1165
                    attr[attrname] = (dbus_interface_annotations
 
1166
                                      (alt_interface)
 
1167
                                      (types.FunctionType
 
1168
                                       (attribute.func_code,
 
1169
                                        attribute.func_globals,
 
1170
                                        attribute.func_name,
 
1171
                                        attribute.func_defaults,
 
1172
                                        attribute.func_closure)))
1201
1173
            if deprecate:
1202
1174
                # Deprecate all alternate interfaces
1203
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1175
                iname="_AlternateDBusNames_interface_annotation{0}"
1204
1176
                for interface_name in interface_names:
1205
 
                    
1206
1177
                    @dbus_interface_annotations(interface_name)
1207
1178
                    def func(self):
1208
1179
                        return { "org.freedesktop.DBus.Deprecated":
1209
 
                                 "true" }
 
1180
                                     "true" }
1210
1181
                    # Find an unused name
1211
1182
                    for aname in (iname.format(i)
1212
1183
                                  for i in itertools.count()):
1216
1187
            if interface_names:
1217
1188
                # Replace the class with a new subclass of it with
1218
1189
                # methods, signals, etc. as created above.
1219
 
                cls = type(b"{}Alternate".format(cls.__name__),
1220
 
                           (cls, ), attr)
 
1190
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1191
                           (cls,), attr)
1221
1192
        return cls
1222
 
    
1223
1193
    return wrapper
1224
1194
 
1225
1195
 
1226
1196
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
 
                            "se.bsnet.fukt.Mandos"})
 
1197
                                "se.bsnet.fukt.Mandos"})
1228
1198
class ClientDBus(Client, DBusObjectWithProperties):
1229
1199
    """A Client class using D-Bus
1230
1200
    
1234
1204
    """
1235
1205
    
1236
1206
    runtime_expansions = (Client.runtime_expansions
1237
 
                          + ("dbus_object_path", ))
1238
 
    
1239
 
    _interface = "se.recompile.Mandos.Client"
 
1207
                          + ("dbus_object_path",))
1240
1208
    
1241
1209
    # dbus.service.Object doesn't use super(), so we can't either.
1242
1210
    
1245
1213
        Client.__init__(self, *args, **kwargs)
1246
1214
        # Only now, when this client is initialized, can it show up on
1247
1215
        # the D-Bus
1248
 
        client_object_name = str(self.name).translate(
 
1216
        client_object_name = unicode(self.name).translate(
1249
1217
            {ord("."): ord("_"),
1250
1218
             ord("-"): ord("_")})
1251
 
        self.dbus_object_path = dbus.ObjectPath(
1252
 
            "/clients/" + client_object_name)
 
1219
        self.dbus_object_path = (dbus.ObjectPath
 
1220
                                 ("/clients/" + client_object_name))
1253
1221
        DBusObjectWithProperties.__init__(self, self.bus,
1254
1222
                                          self.dbus_object_path)
1255
1223
    
1256
 
    def notifychangeproperty(transform_func, dbus_name,
1257
 
                             type_func=lambda x: x,
1258
 
                             variant_level=1,
1259
 
                             invalidate_only=False,
1260
 
                             _interface=_interface):
 
1224
    def notifychangeproperty(transform_func,
 
1225
                             dbus_name, type_func=lambda x: x,
 
1226
                             variant_level=1):
1261
1227
        """ Modify a variable so that it's a property which announces
1262
1228
        its changes to DBus.
1263
1229
        
1268
1234
                   to the D-Bus.  Default: no transform
1269
1235
        variant_level: D-Bus variant level.  Default: 1
1270
1236
        """
1271
 
        attrname = "_{}".format(dbus_name)
1272
 
        
 
1237
        attrname = "_{0}".format(dbus_name)
1273
1238
        def setter(self, value):
1274
1239
            if hasattr(self, "dbus_object_path"):
1275
1240
                if (not hasattr(self, attrname) or
1276
1241
                    type_func(getattr(self, attrname, None))
1277
1242
                    != type_func(value)):
1278
 
                    if invalidate_only:
1279
 
                        self.PropertiesChanged(
1280
 
                            _interface, dbus.Dictionary(),
1281
 
                            dbus.Array((dbus_name, )))
1282
 
                    else:
1283
 
                        dbus_value = transform_func(
1284
 
                            type_func(value),
1285
 
                            variant_level = variant_level)
1286
 
                        self.PropertyChanged(dbus.String(dbus_name),
1287
 
                                             dbus_value)
1288
 
                        self.PropertiesChanged(
1289
 
                            _interface,
1290
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1291
 
                                              dbus_value }),
1292
 
                            dbus.Array())
 
1243
                    dbus_value = transform_func(type_func(value),
 
1244
                                                variant_level
 
1245
                                                =variant_level)
 
1246
                    self.PropertyChanged(dbus.String(dbus_name),
 
1247
                                         dbus_value)
1293
1248
            setattr(self, attrname, value)
1294
1249
        
1295
1250
        return property(lambda self: getattr(self, attrname), setter)
1301
1256
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1257
    last_enabled = notifychangeproperty(datetime_to_dbus,
1303
1258
                                        "LastEnabled")
1304
 
    checker = notifychangeproperty(
1305
 
        dbus.Boolean, "CheckerRunning",
1306
 
        type_func = lambda checker: checker is not None)
 
1259
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1260
                                   type_func = lambda checker:
 
1261
                                       checker is not None)
1307
1262
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1263
                                           "LastCheckedOK")
1309
1264
    last_checker_status = notifychangeproperty(dbus.Int16,
1312
1267
        datetime_to_dbus, "LastApprovalRequest")
1313
1268
    approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1269
                                               "ApprovedByDefault")
1315
 
    approval_delay = notifychangeproperty(
1316
 
        dbus.UInt64, "ApprovalDelay",
1317
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1270
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1271
                                          "ApprovalDelay",
 
1272
                                          type_func =
 
1273
                                          timedelta_to_milliseconds)
1318
1274
    approval_duration = notifychangeproperty(
1319
1275
        dbus.UInt64, "ApprovalDuration",
1320
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1276
        type_func = timedelta_to_milliseconds)
1321
1277
    host = notifychangeproperty(dbus.String, "Host")
1322
 
    timeout = notifychangeproperty(
1323
 
        dbus.UInt64, "Timeout",
1324
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1278
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1279
                                   type_func =
 
1280
                                   timedelta_to_milliseconds)
1325
1281
    extended_timeout = notifychangeproperty(
1326
1282
        dbus.UInt64, "ExtendedTimeout",
1327
 
        type_func = lambda td: td.total_seconds() * 1000)
1328
 
    interval = notifychangeproperty(
1329
 
        dbus.UInt64, "Interval",
1330
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1283
        type_func = timedelta_to_milliseconds)
 
1284
    interval = notifychangeproperty(dbus.UInt64,
 
1285
                                    "Interval",
 
1286
                                    type_func =
 
1287
                                    timedelta_to_milliseconds)
1331
1288
    checker_command = notifychangeproperty(dbus.String, "Checker")
1332
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
 
                                  invalidate_only=True)
1334
1289
    
1335
1290
    del notifychangeproperty
1336
1291
    
1363
1318
                                       *args, **kwargs)
1364
1319
    
1365
1320
    def start_checker(self, *args, **kwargs):
1366
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1321
        old_checker = self.checker
 
1322
        if self.checker is not None:
 
1323
            old_checker_pid = self.checker.pid
 
1324
        else:
 
1325
            old_checker_pid = None
1367
1326
        r = Client.start_checker(self, *args, **kwargs)
1368
1327
        # Only if new checker process was started
1369
1328
        if (self.checker is not None
1378
1337
    
1379
1338
    def approve(self, value=True):
1380
1339
        self.approved = value
1381
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1382
 
                                * 1000), self._reset_approved)
 
1340
        gobject.timeout_add(timedelta_to_milliseconds
 
1341
                            (self.approval_duration),
 
1342
                            self._reset_approved)
1383
1343
        self.send_changedstate()
1384
1344
    
1385
1345
    ## D-Bus methods, signals & properties
 
1346
    _interface = "se.recompile.Mandos.Client"
1386
1347
    
1387
1348
    ## Interfaces
1388
1349
    
 
1350
    @dbus_interface_annotations(_interface)
 
1351
    def _foo(self):
 
1352
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1353
                     "false"}
 
1354
    
1389
1355
    ## Signals
1390
1356
    
1391
1357
    # CheckerCompleted - signal
1401
1367
        pass
1402
1368
    
1403
1369
    # PropertyChanged - signal
1404
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1405
1370
    @dbus.service.signal(_interface, signature="sv")
1406
1371
    def PropertyChanged(self, property, value):
1407
1372
        "D-Bus signal"
1471
1436
        return dbus.Boolean(bool(self.approvals_pending))
1472
1437
    
1473
1438
    # ApprovedByDefault - property
1474
 
    @dbus_service_property(_interface,
1475
 
                           signature="b",
 
1439
    @dbus_service_property(_interface, signature="b",
1476
1440
                           access="readwrite")
1477
1441
    def ApprovedByDefault_dbus_property(self, value=None):
1478
1442
        if value is None:       # get
1480
1444
        self.approved_by_default = bool(value)
1481
1445
    
1482
1446
    # ApprovalDelay - property
1483
 
    @dbus_service_property(_interface,
1484
 
                           signature="t",
 
1447
    @dbus_service_property(_interface, signature="t",
1485
1448
                           access="readwrite")
1486
1449
    def ApprovalDelay_dbus_property(self, value=None):
1487
1450
        if value is None:       # get
1488
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1489
 
                               * 1000)
 
1451
            return dbus.UInt64(self.approval_delay_milliseconds())
1490
1452
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1491
1453
    
1492
1454
    # ApprovalDuration - property
1493
 
    @dbus_service_property(_interface,
1494
 
                           signature="t",
 
1455
    @dbus_service_property(_interface, signature="t",
1495
1456
                           access="readwrite")
1496
1457
    def ApprovalDuration_dbus_property(self, value=None):
1497
1458
        if value is None:       # get
1498
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1499
 
                               * 1000)
 
1459
            return dbus.UInt64(timedelta_to_milliseconds(
 
1460
                    self.approval_duration))
1500
1461
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1501
1462
    
1502
1463
    # Name - property
1510
1471
        return dbus.String(self.fingerprint)
1511
1472
    
1512
1473
    # Host - property
1513
 
    @dbus_service_property(_interface,
1514
 
                           signature="s",
 
1474
    @dbus_service_property(_interface, signature="s",
1515
1475
                           access="readwrite")
1516
1476
    def Host_dbus_property(self, value=None):
1517
1477
        if value is None:       # get
1518
1478
            return dbus.String(self.host)
1519
 
        self.host = str(value)
 
1479
        self.host = unicode(value)
1520
1480
    
1521
1481
    # Created - property
1522
1482
    @dbus_service_property(_interface, signature="s", access="read")
1529
1489
        return datetime_to_dbus(self.last_enabled)
1530
1490
    
1531
1491
    # Enabled - property
1532
 
    @dbus_service_property(_interface,
1533
 
                           signature="b",
 
1492
    @dbus_service_property(_interface, signature="b",
1534
1493
                           access="readwrite")
1535
1494
    def Enabled_dbus_property(self, value=None):
1536
1495
        if value is None:       # get
1541
1500
            self.disable()
1542
1501
    
1543
1502
    # LastCheckedOK - property
1544
 
    @dbus_service_property(_interface,
1545
 
                           signature="s",
 
1503
    @dbus_service_property(_interface, signature="s",
1546
1504
                           access="readwrite")
1547
1505
    def LastCheckedOK_dbus_property(self, value=None):
1548
1506
        if value is not None:
1551
1509
        return datetime_to_dbus(self.last_checked_ok)
1552
1510
    
1553
1511
    # LastCheckerStatus - property
1554
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1512
    @dbus_service_property(_interface, signature="n",
 
1513
                           access="read")
1555
1514
    def LastCheckerStatus_dbus_property(self):
1556
1515
        return dbus.Int16(self.last_checker_status)
1557
1516
    
1566
1525
        return datetime_to_dbus(self.last_approval_request)
1567
1526
    
1568
1527
    # Timeout - property
1569
 
    @dbus_service_property(_interface,
1570
 
                           signature="t",
 
1528
    @dbus_service_property(_interface, signature="t",
1571
1529
                           access="readwrite")
1572
1530
    def Timeout_dbus_property(self, value=None):
1573
1531
        if value is None:       # get
1574
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1532
            return dbus.UInt64(self.timeout_milliseconds())
1575
1533
        old_timeout = self.timeout
1576
1534
        self.timeout = datetime.timedelta(0, 0, 0, value)
1577
1535
        # Reschedule disabling
1586
1544
                    is None):
1587
1545
                    return
1588
1546
                gobject.source_remove(self.disable_initiator_tag)
1589
 
                self.disable_initiator_tag = gobject.timeout_add(
1590
 
                    int((self.expires - now).total_seconds() * 1000),
1591
 
                    self.disable)
 
1547
                self.disable_initiator_tag = (
 
1548
                    gobject.timeout_add(
 
1549
                        timedelta_to_milliseconds(self.expires - now),
 
1550
                        self.disable))
1592
1551
    
1593
1552
    # ExtendedTimeout - property
1594
 
    @dbus_service_property(_interface,
1595
 
                           signature="t",
 
1553
    @dbus_service_property(_interface, signature="t",
1596
1554
                           access="readwrite")
1597
1555
    def ExtendedTimeout_dbus_property(self, value=None):
1598
1556
        if value is None:       # get
1599
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1600
 
                               * 1000)
 
1557
            return dbus.UInt64(self.extended_timeout_milliseconds())
1601
1558
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1602
1559
    
1603
1560
    # Interval - property
1604
 
    @dbus_service_property(_interface,
1605
 
                           signature="t",
 
1561
    @dbus_service_property(_interface, signature="t",
1606
1562
                           access="readwrite")
1607
1563
    def Interval_dbus_property(self, value=None):
1608
1564
        if value is None:       # get
1609
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1565
            return dbus.UInt64(self.interval_milliseconds())
1610
1566
        self.interval = datetime.timedelta(0, 0, 0, value)
1611
1567
        if getattr(self, "checker_initiator_tag", None) is None:
1612
1568
            return
1613
1569
        if self.enabled:
1614
1570
            # Reschedule checker run
1615
1571
            gobject.source_remove(self.checker_initiator_tag)
1616
 
            self.checker_initiator_tag = gobject.timeout_add(
1617
 
                value, self.start_checker)
1618
 
            self.start_checker() # Start one now, too
 
1572
            self.checker_initiator_tag = (gobject.timeout_add
 
1573
                                          (value, self.start_checker))
 
1574
            self.start_checker()    # Start one now, too
1619
1575
    
1620
1576
    # Checker - property
1621
 
    @dbus_service_property(_interface,
1622
 
                           signature="s",
 
1577
    @dbus_service_property(_interface, signature="s",
1623
1578
                           access="readwrite")
1624
1579
    def Checker_dbus_property(self, value=None):
1625
1580
        if value is None:       # get
1626
1581
            return dbus.String(self.checker_command)
1627
 
        self.checker_command = str(value)
 
1582
        self.checker_command = unicode(value)
1628
1583
    
1629
1584
    # CheckerRunning - property
1630
 
    @dbus_service_property(_interface,
1631
 
                           signature="b",
 
1585
    @dbus_service_property(_interface, signature="b",
1632
1586
                           access="readwrite")
1633
1587
    def CheckerRunning_dbus_property(self, value=None):
1634
1588
        if value is None:       # get
1644
1598
        return self.dbus_object_path # is already a dbus.ObjectPath
1645
1599
    
1646
1600
    # Secret = property
1647
 
    @dbus_service_property(_interface,
1648
 
                           signature="ay",
1649
 
                           access="write",
1650
 
                           byte_arrays=True)
 
1601
    @dbus_service_property(_interface, signature="ay",
 
1602
                           access="write", byte_arrays=True)
1651
1603
    def Secret_dbus_property(self, value):
1652
 
        self.secret = bytes(value)
 
1604
        self.secret = str(value)
1653
1605
    
1654
1606
    del _interface
1655
1607
 
1669
1621
        if data[0] == 'data':
1670
1622
            return data[1]
1671
1623
        if data[0] == 'function':
1672
 
            
1673
1624
            def func(*args, **kwargs):
1674
1625
                self._pipe.send(('funcall', name, args, kwargs))
1675
1626
                return self._pipe.recv()[1]
1676
 
            
1677
1627
            return func
1678
1628
    
1679
1629
    def __setattr__(self, name, value):
1691
1641
    def handle(self):
1692
1642
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1693
1643
            logger.info("TCP connection from: %s",
1694
 
                        str(self.client_address))
 
1644
                        unicode(self.client_address))
1695
1645
            logger.debug("Pipe FD: %d",
1696
1646
                         self.server.child_pipe.fileno())
1697
1647
            
1698
 
            session = gnutls.connection.ClientSession(
1699
 
                self.request, gnutls.connection .X509Credentials())
 
1648
            session = (gnutls.connection
 
1649
                       .ClientSession(self.request,
 
1650
                                      gnutls.connection
 
1651
                                      .X509Credentials()))
1700
1652
            
1701
1653
            # Note: gnutls.connection.X509Credentials is really a
1702
1654
            # generic GnuTLS certificate credentials object so long as
1711
1663
            priority = self.server.gnutls_priority
1712
1664
            if priority is None:
1713
1665
                priority = "NORMAL"
1714
 
            gnutls.library.functions.gnutls_priority_set_direct(
1715
 
                session._c_object, priority, None)
 
1666
            (gnutls.library.functions
 
1667
             .gnutls_priority_set_direct(session._c_object,
 
1668
                                         priority, None))
1716
1669
            
1717
1670
            # Start communication using the Mandos protocol
1718
1671
            # Get protocol number
1720
1673
            logger.debug("Protocol version: %r", line)
1721
1674
            try:
1722
1675
                if int(line.strip().split()[0]) > 1:
1723
 
                    raise RuntimeError(line)
 
1676
                    raise RuntimeError
1724
1677
            except (ValueError, IndexError, RuntimeError) as error:
1725
1678
                logger.error("Unknown protocol version: %s", error)
1726
1679
                return
1738
1691
            approval_required = False
1739
1692
            try:
1740
1693
                try:
1741
 
                    fpr = self.fingerprint(
1742
 
                        self.peer_certificate(session))
 
1694
                    fpr = self.fingerprint(self.peer_certificate
 
1695
                                           (session))
1743
1696
                except (TypeError,
1744
1697
                        gnutls.errors.GNUTLSError) as error:
1745
1698
                    logger.warning("Bad certificate: %s", error)
1760
1713
                while True:
1761
1714
                    if not client.enabled:
1762
1715
                        logger.info("Client %s is disabled",
1763
 
                                    client.name)
 
1716
                                       client.name)
1764
1717
                        if self.server.use_dbus:
1765
1718
                            # Emit D-Bus signal
1766
1719
                            client.Rejected("Disabled")
1775
1728
                        if self.server.use_dbus:
1776
1729
                            # Emit D-Bus signal
1777
1730
                            client.NeedApproval(
1778
 
                                client.approval_delay.total_seconds()
1779
 
                                * 1000, client.approved_by_default)
 
1731
                                client.approval_delay_milliseconds(),
 
1732
                                client.approved_by_default)
1780
1733
                    else:
1781
1734
                        logger.warning("Client %s was not approved",
1782
1735
                                       client.name)
1788
1741
                    #wait until timeout or approved
1789
1742
                    time = datetime.datetime.now()
1790
1743
                    client.changedstate.acquire()
1791
 
                    client.changedstate.wait(delay.total_seconds())
 
1744
                    client.changedstate.wait(
 
1745
                        float(timedelta_to_milliseconds(delay)
 
1746
                              / 1000))
1792
1747
                    client.changedstate.release()
1793
1748
                    time2 = datetime.datetime.now()
1794
1749
                    if (time2 - time) >= delay:
1813
1768
                        logger.warning("gnutls send failed",
1814
1769
                                       exc_info=error)
1815
1770
                        return
1816
 
                    logger.debug("Sent: %d, remaining: %d", sent,
1817
 
                                 len(client.secret) - (sent_size
1818
 
                                                       + sent))
 
1771
                    logger.debug("Sent: %d, remaining: %d",
 
1772
                                 sent, len(client.secret)
 
1773
                                 - (sent_size + sent))
1819
1774
                    sent_size += sent
1820
1775
                
1821
1776
                logger.info("Sending secret to %s", client.name)
1838
1793
    def peer_certificate(session):
1839
1794
        "Return the peer's OpenPGP certificate as a bytestring"
1840
1795
        # If not an OpenPGP certificate...
1841
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1842
 
                session._c_object)
 
1796
        if (gnutls.library.functions
 
1797
            .gnutls_certificate_type_get(session._c_object)
1843
1798
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1799
            # ...do the normal thing
1845
1800
            return session.peer_certificate
1859
1814
    def fingerprint(openpgp):
1860
1815
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1816
        # New GnuTLS "datum" with the OpenPGP public key
1862
 
        datum = gnutls.library.types.gnutls_datum_t(
1863
 
            ctypes.cast(ctypes.c_char_p(openpgp),
1864
 
                        ctypes.POINTER(ctypes.c_ubyte)),
1865
 
            ctypes.c_uint(len(openpgp)))
 
1817
        datum = (gnutls.library.types
 
1818
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1819
                                             ctypes.POINTER
 
1820
                                             (ctypes.c_ubyte)),
 
1821
                                 ctypes.c_uint(len(openpgp))))
1866
1822
        # New empty GnuTLS certificate
1867
1823
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1869
 
            ctypes.byref(crt))
 
1824
        (gnutls.library.functions
 
1825
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1826
        # Import the OpenPGP public key into the certificate
1871
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1872
 
            crt, ctypes.byref(datum),
1873
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1827
        (gnutls.library.functions
 
1828
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1829
                                    gnutls.library.constants
 
1830
                                    .GNUTLS_OPENPGP_FMT_RAW))
1874
1831
        # Verify the self signature in the key
1875
1832
        crtverify = ctypes.c_uint()
1876
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
 
            crt, 0, ctypes.byref(crtverify))
 
1833
        (gnutls.library.functions
 
1834
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1835
                                         ctypes.byref(crtverify)))
1878
1836
        if crtverify.value != 0:
1879
1837
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
 
            raise gnutls.errors.CertificateSecurityError(
1881
 
                "Verify failed")
 
1838
            raise (gnutls.errors.CertificateSecurityError
 
1839
                   ("Verify failed"))
1882
1840
        # New buffer for the fingerprint
1883
1841
        buf = ctypes.create_string_buffer(20)
1884
1842
        buf_len = ctypes.c_size_t()
1885
1843
        # Get the fingerprint from the certificate into the buffer
1886
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1844
        (gnutls.library.functions
 
1845
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1846
                                             ctypes.byref(buf_len)))
1888
1847
        # Deinit the certificate
1889
1848
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1849
        # Convert the buffer to a Python bytestring
1896
1855
 
1897
1856
class MultiprocessingMixIn(object):
1898
1857
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1899
 
    
1900
1858
    def sub_process_main(self, request, address):
1901
1859
        try:
1902
1860
            self.finish_request(request, address)
1914
1872
 
1915
1873
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1916
1874
    """ adds a pipe to the MixIn """
1917
 
    
1918
1875
    def process_request(self, request, client_address):
1919
1876
        """Overrides and wraps the original process_request().
1920
1877
        
1929
1886
    
1930
1887
    def add_pipe(self, parent_pipe, proc):
1931
1888
        """Dummy function; override as necessary"""
1932
 
        raise NotImplementedError()
 
1889
        raise NotImplementedError
1933
1890
 
1934
1891
 
1935
1892
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1941
1898
        interface:      None or a network interface name (string)
1942
1899
        use_ipv6:       Boolean; to use IPv6 or not
1943
1900
    """
1944
 
    
1945
1901
    def __init__(self, server_address, RequestHandlerClass,
1946
 
                 interface=None,
1947
 
                 use_ipv6=True,
1948
 
                 socketfd=None):
 
1902
                 interface=None, use_ipv6=True, socketfd=None):
1949
1903
        """If socketfd is set, use that file descriptor instead of
1950
1904
        creating a new one with socket.socket().
1951
1905
        """
1992
1946
                             self.interface)
1993
1947
            else:
1994
1948
                try:
1995
 
                    self.socket.setsockopt(
1996
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
 
                        (self.interface + "\0").encode("utf-8"))
 
1949
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1950
                                           SO_BINDTODEVICE,
 
1951
                                           str(self.interface + '\0'))
1998
1952
                except socket.error as error:
1999
1953
                    if error.errno == errno.EPERM:
2000
1954
                        logger.error("No permission to bind to"
2014
1968
                if self.address_family == socket.AF_INET6:
2015
1969
                    any_address = "::" # in6addr_any
2016
1970
                else:
2017
 
                    any_address = "0.0.0.0" # INADDR_ANY
 
1971
                    any_address = socket.INADDR_ANY
2018
1972
                self.server_address = (any_address,
2019
1973
                                       self.server_address[1])
2020
1974
            elif not self.server_address[1]:
2021
 
                self.server_address = (self.server_address[0], 0)
 
1975
                self.server_address = (self.server_address[0],
 
1976
                                       0)
2022
1977
#                 if self.interface:
2023
1978
#                     self.server_address = (self.server_address[0],
2024
1979
#                                            0, # port
2038
1993
    
2039
1994
    Assumes a gobject.MainLoop event loop.
2040
1995
    """
2041
 
    
2042
1996
    def __init__(self, server_address, RequestHandlerClass,
2043
 
                 interface=None,
2044
 
                 use_ipv6=True,
2045
 
                 clients=None,
2046
 
                 gnutls_priority=None,
2047
 
                 use_dbus=True,
2048
 
                 socketfd=None):
 
1997
                 interface=None, use_ipv6=True, clients=None,
 
1998
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2049
1999
        self.enabled = False
2050
2000
        self.clients = clients
2051
2001
        if self.clients is None:
2057
2007
                                interface = interface,
2058
2008
                                use_ipv6 = use_ipv6,
2059
2009
                                socketfd = socketfd)
2060
 
    
2061
2010
    def server_activate(self):
2062
2011
        if self.enabled:
2063
2012
            return socketserver.TCPServer.server_activate(self)
2067
2016
    
2068
2017
    def add_pipe(self, parent_pipe, proc):
2069
2018
        # Call "handle_ipc" for both data and EOF events
2070
 
        gobject.io_add_watch(
2071
 
            parent_pipe.fileno(),
2072
 
            gobject.IO_IN | gobject.IO_HUP,
2073
 
            functools.partial(self.handle_ipc,
2074
 
                              parent_pipe = parent_pipe,
2075
 
                              proc = proc))
 
2019
        gobject.io_add_watch(parent_pipe.fileno(),
 
2020
                             gobject.IO_IN | gobject.IO_HUP,
 
2021
                             functools.partial(self.handle_ipc,
 
2022
                                               parent_pipe =
 
2023
                                               parent_pipe,
 
2024
                                               proc = proc))
2076
2025
    
2077
 
    def handle_ipc(self, source, condition,
2078
 
                   parent_pipe=None,
2079
 
                   proc = None,
2080
 
                   client_object=None):
 
2026
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2027
                   proc = None, client_object=None):
2081
2028
        # error, or the other end of multiprocessing.Pipe has closed
2082
2029
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2030
            # Wait for other process to exit
2106
2053
                parent_pipe.send(False)
2107
2054
                return False
2108
2055
            
2109
 
            gobject.io_add_watch(
2110
 
                parent_pipe.fileno(),
2111
 
                gobject.IO_IN | gobject.IO_HUP,
2112
 
                functools.partial(self.handle_ipc,
2113
 
                                  parent_pipe = parent_pipe,
2114
 
                                  proc = proc,
2115
 
                                  client_object = client))
 
2056
            gobject.io_add_watch(parent_pipe.fileno(),
 
2057
                                 gobject.IO_IN | gobject.IO_HUP,
 
2058
                                 functools.partial(self.handle_ipc,
 
2059
                                                   parent_pipe =
 
2060
                                                   parent_pipe,
 
2061
                                                   proc = proc,
 
2062
                                                   client_object =
 
2063
                                                   client))
2116
2064
            parent_pipe.send(True)
2117
2065
            # remove the old hook in favor of the new above hook on
2118
2066
            # same fileno
2124
2072
            
2125
2073
            parent_pipe.send(('data', getattr(client_object,
2126
2074
                                              funcname)(*args,
2127
 
                                                        **kwargs)))
 
2075
                                                         **kwargs)))
2128
2076
        
2129
2077
        if command == 'getattr':
2130
2078
            attrname = request[1]
2131
2079
            if callable(client_object.__getattribute__(attrname)):
2132
 
                parent_pipe.send(('function', ))
 
2080
                parent_pipe.send(('function',))
2133
2081
            else:
2134
 
                parent_pipe.send((
2135
 
                    'data', client_object.__getattribute__(attrname)))
 
2082
                parent_pipe.send(('data', client_object
 
2083
                                  .__getattribute__(attrname)))
2136
2084
        
2137
2085
        if command == 'setattr':
2138
2086
            attrname = request[1]
2142
2090
        return True
2143
2091
 
2144
2092
 
2145
 
def rfc3339_duration_to_delta(duration):
2146
 
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2147
 
    
2148
 
    >>> rfc3339_duration_to_delta("P7D")
2149
 
    datetime.timedelta(7)
2150
 
    >>> rfc3339_duration_to_delta("PT60S")
2151
 
    datetime.timedelta(0, 60)
2152
 
    >>> rfc3339_duration_to_delta("PT60M")
2153
 
    datetime.timedelta(0, 3600)
2154
 
    >>> rfc3339_duration_to_delta("PT24H")
2155
 
    datetime.timedelta(1)
2156
 
    >>> rfc3339_duration_to_delta("P1W")
2157
 
    datetime.timedelta(7)
2158
 
    >>> rfc3339_duration_to_delta("PT5M30S")
2159
 
    datetime.timedelta(0, 330)
2160
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2161
 
    datetime.timedelta(1, 200)
2162
 
    """
2163
 
    
2164
 
    # Parsing an RFC 3339 duration with regular expressions is not
2165
 
    # possible - there would have to be multiple places for the same
2166
 
    # values, like seconds.  The current code, while more esoteric, is
2167
 
    # cleaner without depending on a parsing library.  If Python had a
2168
 
    # built-in library for parsing we would use it, but we'd like to
2169
 
    # avoid excessive use of external libraries.
2170
 
    
2171
 
    # New type for defining tokens, syntax, and semantics all-in-one
2172
 
    Token = collections.namedtuple("Token",
2173
 
                                   ("regexp", # To match token; if
2174
 
                                              # "value" is not None,
2175
 
                                              # must have a "group"
2176
 
                                              # containing digits
2177
 
                                    "value",  # datetime.timedelta or
2178
 
                                              # None
2179
 
                                    "followers")) # Tokens valid after
2180
 
                                                  # this token
2181
 
    Token = collections.namedtuple("Token", (
2182
 
        "regexp",  # To match token; if "value" is not None, must have
2183
 
                   # a "group" containing digits
2184
 
        "value",   # datetime.timedelta or None
2185
 
        "followers"))           # Tokens valid after this token
2186
 
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
 
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2188
 
    token_end = Token(re.compile(r"$"), None, frozenset())
2189
 
    token_second = Token(re.compile(r"(\d+)S"),
2190
 
                         datetime.timedelta(seconds=1),
2191
 
                         frozenset((token_end, )))
2192
 
    token_minute = Token(re.compile(r"(\d+)M"),
2193
 
                         datetime.timedelta(minutes=1),
2194
 
                         frozenset((token_second, token_end)))
2195
 
    token_hour = Token(re.compile(r"(\d+)H"),
2196
 
                       datetime.timedelta(hours=1),
2197
 
                       frozenset((token_minute, token_end)))
2198
 
    token_time = Token(re.compile(r"T"),
2199
 
                       None,
2200
 
                       frozenset((token_hour, token_minute,
2201
 
                                  token_second)))
2202
 
    token_day = Token(re.compile(r"(\d+)D"),
2203
 
                      datetime.timedelta(days=1),
2204
 
                      frozenset((token_time, token_end)))
2205
 
    token_month = Token(re.compile(r"(\d+)M"),
2206
 
                        datetime.timedelta(weeks=4),
2207
 
                        frozenset((token_day, token_end)))
2208
 
    token_year = Token(re.compile(r"(\d+)Y"),
2209
 
                       datetime.timedelta(weeks=52),
2210
 
                       frozenset((token_month, token_end)))
2211
 
    token_week = Token(re.compile(r"(\d+)W"),
2212
 
                       datetime.timedelta(weeks=1),
2213
 
                       frozenset((token_end, )))
2214
 
    token_duration = Token(re.compile(r"P"), None,
2215
 
                           frozenset((token_year, token_month,
2216
 
                                      token_day, token_time,
2217
 
                                      token_week)))
2218
 
    # Define starting values
2219
 
    value = datetime.timedelta() # Value so far
2220
 
    found_token = None
2221
 
    followers = frozenset((token_duration,)) # Following valid tokens
2222
 
    s = duration                # String left to parse
2223
 
    # Loop until end token is found
2224
 
    while found_token is not token_end:
2225
 
        # Search for any currently valid tokens
2226
 
        for token in followers:
2227
 
            match = token.regexp.match(s)
2228
 
            if match is not None:
2229
 
                # Token found
2230
 
                if token.value is not None:
2231
 
                    # Value found, parse digits
2232
 
                    factor = int(match.group(1), 10)
2233
 
                    # Add to value so far
2234
 
                    value += factor * token.value
2235
 
                # Strip token from string
2236
 
                s = token.regexp.sub("", s, 1)
2237
 
                # Go to found token
2238
 
                found_token = token
2239
 
                # Set valid next tokens
2240
 
                followers = found_token.followers
2241
 
                break
2242
 
        else:
2243
 
            # No currently valid tokens were found
2244
 
            raise ValueError("Invalid RFC 3339 duration")
2245
 
    # End token found
2246
 
    return value
2247
 
 
2248
 
 
2249
2093
def string_to_delta(interval):
2250
2094
    """Parse a string and return a datetime.timedelta
2251
2095
    
2262
2106
    >>> string_to_delta('5m 30s')
2263
2107
    datetime.timedelta(0, 330)
2264
2108
    """
2265
 
    
2266
 
    try:
2267
 
        return rfc3339_duration_to_delta(interval)
2268
 
    except ValueError:
2269
 
        pass
2270
 
    
2271
2109
    timevalue = datetime.timedelta(0)
2272
2110
    for s in interval.split():
2273
2111
        try:
2274
 
            suffix = s[-1]
 
2112
            suffix = unicode(s[-1])
2275
2113
            value = int(s[:-1])
2276
2114
            if suffix == "d":
2277
2115
                delta = datetime.timedelta(value)
2284
2122
            elif suffix == "w":
2285
2123
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2286
2124
            else:
2287
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
2288
 
        except IndexError as e:
 
2125
                raise ValueError("Unknown suffix {0!r}"
 
2126
                                 .format(suffix))
 
2127
        except (ValueError, IndexError) as e:
2289
2128
            raise ValueError(*(e.args))
2290
2129
        timevalue += delta
2291
2130
    return timevalue
2307
2146
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2147
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
2148
            raise OSError(errno.ENODEV,
2310
 
                          "{} not a character device"
 
2149
                          "{0} not a character device"
2311
2150
                          .format(os.devnull))
2312
2151
        os.dup2(null, sys.stdin.fileno())
2313
2152
        os.dup2(null, sys.stdout.fileno())
2323
2162
    
2324
2163
    parser = argparse.ArgumentParser()
2325
2164
    parser.add_argument("-v", "--version", action="version",
2326
 
                        version = "%(prog)s {}".format(version),
 
2165
                        version = "%(prog)s {0}".format(version),
2327
2166
                        help="show version number and exit")
2328
2167
    parser.add_argument("-i", "--interface", metavar="IF",
2329
2168
                        help="Bind to interface IF")
2335
2174
                        help="Run self-test")
2336
2175
    parser.add_argument("--debug", action="store_true",
2337
2176
                        help="Debug mode; run in foreground and log"
2338
 
                        " to terminal", default=None)
 
2177
                        " to terminal")
2339
2178
    parser.add_argument("--debuglevel", metavar="LEVEL",
2340
2179
                        help="Debug level for stdout output")
2341
2180
    parser.add_argument("--priority", help="GnuTLS"
2348
2187
                        " files")
2349
2188
    parser.add_argument("--no-dbus", action="store_false",
2350
2189
                        dest="use_dbus", help="Do not provide D-Bus"
2351
 
                        " system bus interface", default=None)
 
2190
                        " system bus interface")
2352
2191
    parser.add_argument("--no-ipv6", action="store_false",
2353
 
                        dest="use_ipv6", help="Do not use IPv6",
2354
 
                        default=None)
 
2192
                        dest="use_ipv6", help="Do not use IPv6")
2355
2193
    parser.add_argument("--no-restore", action="store_false",
2356
2194
                        dest="restore", help="Do not restore stored"
2357
 
                        " state", default=None)
 
2195
                        " state")
2358
2196
    parser.add_argument("--socket", type=int,
2359
2197
                        help="Specify a file descriptor to a network"
2360
2198
                        " socket to use instead of creating one")
2361
2199
    parser.add_argument("--statedir", metavar="DIR",
2362
2200
                        help="Directory to save/restore state in")
2363
2201
    parser.add_argument("--foreground", action="store_true",
2364
 
                        help="Run in foreground", default=None)
2365
 
    parser.add_argument("--no-zeroconf", action="store_false",
2366
 
                        dest="zeroconf", help="Do not use Zeroconf",
2367
 
                        default=None)
 
2202
                        help="Run in foreground")
2368
2203
    
2369
2204
    options = parser.parse_args()
2370
2205
    
2371
2206
    if options.check:
2372
2207
        import doctest
2373
 
        fail_count, test_count = doctest.testmod()
2374
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2208
        doctest.testmod()
 
2209
        sys.exit()
2375
2210
    
2376
2211
    # Default values for config file for server-global settings
2377
2212
    server_defaults = { "interface": "",
2379
2214
                        "port": "",
2380
2215
                        "debug": "False",
2381
2216
                        "priority":
2382
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2383
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2217
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
2384
2218
                        "servicename": "Mandos",
2385
2219
                        "use_dbus": "True",
2386
2220
                        "use_ipv6": "True",
2389
2223
                        "socket": "",
2390
2224
                        "statedir": "/var/lib/mandos",
2391
2225
                        "foreground": "False",
2392
 
                        "zeroconf": "True",
2393
 
                    }
 
2226
                        }
2394
2227
    
2395
2228
    # Parse config file for server-global settings
2396
2229
    server_config = configparser.SafeConfigParser(server_defaults)
2397
2230
    del server_defaults
2398
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2231
    server_config.read(os.path.join(options.configdir,
 
2232
                                    "mandos.conf"))
2399
2233
    # Convert the SafeConfigParser object to a dict
2400
2234
    server_settings = server_config.defaults()
2401
2235
    # Use the appropriate methods on the non-string config options
2419
2253
    # Override the settings from the config file with command line
2420
2254
    # options, if set.
2421
2255
    for option in ("interface", "address", "port", "debug",
2422
 
                   "priority", "servicename", "configdir", "use_dbus",
2423
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2424
 
                   "socket", "foreground", "zeroconf"):
 
2256
                   "priority", "servicename", "configdir",
 
2257
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2258
                   "statedir", "socket", "foreground"):
2425
2259
        value = getattr(options, option)
2426
2260
        if value is not None:
2427
2261
            server_settings[option] = value
2428
2262
    del options
2429
2263
    # Force all strings to be unicode
2430
2264
    for option in server_settings.keys():
2431
 
        if isinstance(server_settings[option], bytes):
2432
 
            server_settings[option] = (server_settings[option]
2433
 
                                       .decode("utf-8"))
2434
 
    # Force all boolean options to be boolean
2435
 
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2436
 
                   "foreground", "zeroconf"):
2437
 
        server_settings[option] = bool(server_settings[option])
 
2265
        if type(server_settings[option]) is str:
 
2266
            server_settings[option] = unicode(server_settings[option])
2438
2267
    # Debug implies foreground
2439
2268
    if server_settings["debug"]:
2440
2269
        server_settings["foreground"] = True
2442
2271
    
2443
2272
    ##################################################################
2444
2273
    
2445
 
    if (not server_settings["zeroconf"]
2446
 
        and not (server_settings["port"]
2447
 
                 or server_settings["socket"] != "")):
2448
 
        parser.error("Needs port or socket to work without Zeroconf")
2449
 
    
2450
2274
    # For convenience
2451
2275
    debug = server_settings["debug"]
2452
2276
    debuglevel = server_settings["debuglevel"]
2455
2279
    stored_state_path = os.path.join(server_settings["statedir"],
2456
2280
                                     stored_state_file)
2457
2281
    foreground = server_settings["foreground"]
2458
 
    zeroconf = server_settings["zeroconf"]
2459
2282
    
2460
2283
    if debug:
2461
2284
        initlogger(debug, logging.DEBUG)
2467
2290
            initlogger(debug, level)
2468
2291
    
2469
2292
    if server_settings["servicename"] != "Mandos":
2470
 
        syslogger.setFormatter(
2471
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2472
 
                              ' %(levelname)s: %(message)s'.format(
2473
 
                                  server_settings["servicename"])))
 
2293
        syslogger.setFormatter(logging.Formatter
 
2294
                               ('Mandos ({0}) [%(process)d]:'
 
2295
                                ' %(levelname)s: %(message)s'
 
2296
                                .format(server_settings
 
2297
                                        ["servicename"])))
2474
2298
    
2475
2299
    # Parse config file with clients
2476
2300
    client_config = configparser.SafeConfigParser(Client
2481
2305
    global mandos_dbus_service
2482
2306
    mandos_dbus_service = None
2483
2307
    
2484
 
    socketfd = None
2485
 
    if server_settings["socket"] != "":
2486
 
        socketfd = server_settings["socket"]
2487
 
    tcp_server = MandosServer(
2488
 
        (server_settings["address"], server_settings["port"]),
2489
 
        ClientHandler,
2490
 
        interface=(server_settings["interface"] or None),
2491
 
        use_ipv6=use_ipv6,
2492
 
        gnutls_priority=server_settings["priority"],
2493
 
        use_dbus=use_dbus,
2494
 
        socketfd=socketfd)
 
2308
    tcp_server = MandosServer((server_settings["address"],
 
2309
                               server_settings["port"]),
 
2310
                              ClientHandler,
 
2311
                              interface=(server_settings["interface"]
 
2312
                                         or None),
 
2313
                              use_ipv6=use_ipv6,
 
2314
                              gnutls_priority=
 
2315
                              server_settings["priority"],
 
2316
                              use_dbus=use_dbus,
 
2317
                              socketfd=(server_settings["socket"]
 
2318
                                        or None))
2495
2319
    if not foreground:
2496
 
        pidfilename = "/run/mandos.pid"
2497
 
        if not os.path.isdir("/run/."):
2498
 
            pidfilename = "/var/run/mandos.pid"
 
2320
        pidfilename = "/var/run/mandos.pid"
2499
2321
        pidfile = None
2500
2322
        try:
2501
2323
            pidfile = open(pidfilename, "w")
2518
2340
        os.setuid(uid)
2519
2341
    except OSError as error:
2520
2342
        if error.errno != errno.EPERM:
2521
 
            raise
 
2343
            raise error
2522
2344
    
2523
2345
    if debug:
2524
2346
        # Enable all possible GnuTLS debugging
2531
2353
        def debug_gnutls(level, string):
2532
2354
            logger.debug("GnuTLS: %s", string[:-1])
2533
2355
        
2534
 
        gnutls.library.functions.gnutls_global_set_log_function(
2535
 
            debug_gnutls)
 
2356
        (gnutls.library.functions
 
2357
         .gnutls_global_set_log_function(debug_gnutls))
2536
2358
        
2537
2359
        # Redirect stdin so all checkers get /dev/null
2538
2360
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2558
2380
    if use_dbus:
2559
2381
        try:
2560
2382
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2561
 
                                            bus,
2562
 
                                            do_not_queue=True)
2563
 
            old_bus_name = dbus.service.BusName(
2564
 
                "se.bsnet.fukt.Mandos", bus,
2565
 
                do_not_queue=True)
 
2383
                                            bus, do_not_queue=True)
 
2384
            old_bus_name = (dbus.service.BusName
 
2385
                            ("se.bsnet.fukt.Mandos", bus,
 
2386
                             do_not_queue=True))
2566
2387
        except dbus.exceptions.NameExistsException as e:
2567
2388
            logger.error("Disabling D-Bus:", exc_info=e)
2568
2389
            use_dbus = False
2569
2390
            server_settings["use_dbus"] = False
2570
2391
            tcp_server.use_dbus = False
2571
 
    if zeroconf:
2572
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2573
 
        service = AvahiServiceToSyslog(
2574
 
            name = server_settings["servicename"],
2575
 
            servicetype = "_mandos._tcp",
2576
 
            protocol = protocol,
2577
 
            bus = bus)
2578
 
        if server_settings["interface"]:
2579
 
            service.interface = if_nametoindex(
2580
 
                server_settings["interface"].encode("utf-8"))
 
2392
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2393
    service = AvahiServiceToSyslog(name =
 
2394
                                   server_settings["servicename"],
 
2395
                                   servicetype = "_mandos._tcp",
 
2396
                                   protocol = protocol, bus = bus)
 
2397
    if server_settings["interface"]:
 
2398
        service.interface = (if_nametoindex
 
2399
                             (str(server_settings["interface"])))
2581
2400
    
2582
2401
    global multiprocessing_manager
2583
2402
    multiprocessing_manager = multiprocessing.Manager()
2590
2409
    old_client_settings = {}
2591
2410
    clients_data = {}
2592
2411
    
2593
 
    # This is used to redirect stdout and stderr for checker processes
2594
 
    global wnull
2595
 
    wnull = open(os.devnull, "w") # A writable /dev/null
2596
 
    # Only used if server is running in foreground but not in debug
2597
 
    # mode
2598
 
    if debug or not foreground:
2599
 
        wnull.close()
2600
 
    
2601
2412
    # Get client data and settings from last running state.
2602
2413
    if server_settings["restore"]:
2603
2414
        try:
2604
2415
            with open(stored_state_path, "rb") as stored_state:
2605
 
                clients_data, old_client_settings = pickle.load(
2606
 
                    stored_state)
 
2416
                clients_data, old_client_settings = (pickle.load
 
2417
                                                     (stored_state))
2607
2418
            os.remove(stored_state_path)
2608
2419
        except IOError as e:
2609
2420
            if e.errno == errno.ENOENT:
2610
 
                logger.warning("Could not load persistent state:"
2611
 
                               " {}".format(os.strerror(e.errno)))
 
2421
                logger.warning("Could not load persistent state: {0}"
 
2422
                                .format(os.strerror(e.errno)))
2612
2423
            else:
2613
2424
                logger.critical("Could not load persistent state:",
2614
2425
                                exc_info=e)
2615
2426
                raise
2616
2427
        except EOFError as e:
2617
2428
            logger.warning("Could not load persistent state: "
2618
 
                           "EOFError:",
2619
 
                           exc_info=e)
 
2429
                           "EOFError:", exc_info=e)
2620
2430
    
2621
2431
    with PGPEngine() as pgp:
2622
 
        for client_name, client in clients_data.items():
2623
 
            # Skip removed clients
2624
 
            if client_name not in client_settings:
2625
 
                continue
2626
 
            
 
2432
        for client_name, client in clients_data.iteritems():
2627
2433
            # Decide which value to use after restoring saved state.
2628
2434
            # We have three different values: Old config file,
2629
2435
            # new config file, and saved state.
2634
2440
                    # For each value in new config, check if it
2635
2441
                    # differs from the old config value (Except for
2636
2442
                    # the "secret" attribute)
2637
 
                    if (name != "secret"
2638
 
                        and (value !=
2639
 
                             old_client_settings[client_name][name])):
 
2443
                    if (name != "secret" and
 
2444
                        value != old_client_settings[client_name]
 
2445
                        [name]):
2640
2446
                        client[name] = value
2641
2447
                except KeyError:
2642
2448
                    pass
2650
2456
                if datetime.datetime.utcnow() >= client["expires"]:
2651
2457
                    if not client["last_checked_ok"]:
2652
2458
                        logger.warning(
2653
 
                            "disabling client {} - Client never "
2654
 
                            "performed a successful checker".format(
2655
 
                                client_name))
 
2459
                            "disabling client {0} - Client never "
 
2460
                            "performed a successful checker"
 
2461
                            .format(client_name))
2656
2462
                        client["enabled"] = False
2657
2463
                    elif client["last_checker_status"] != 0:
2658
2464
                        logger.warning(
2659
 
                            "disabling client {} - Client last"
2660
 
                            " checker failed with error code"
2661
 
                            " {}".format(
2662
 
                                client_name,
2663
 
                                client["last_checker_status"]))
 
2465
                            "disabling client {0} - Client "
 
2466
                            "last checker failed with error code {1}"
 
2467
                            .format(client_name,
 
2468
                                    client["last_checker_status"]))
2664
2469
                        client["enabled"] = False
2665
2470
                    else:
2666
 
                        client["expires"] = (
2667
 
                            datetime.datetime.utcnow()
2668
 
                            + client["timeout"])
 
2471
                        client["expires"] = (datetime.datetime
 
2472
                                             .utcnow()
 
2473
                                             + client["timeout"])
2669
2474
                        logger.debug("Last checker succeeded,"
2670
 
                                     " keeping {} enabled".format(
2671
 
                                         client_name))
 
2475
                                     " keeping {0} enabled"
 
2476
                                     .format(client_name))
2672
2477
            try:
2673
 
                client["secret"] = pgp.decrypt(
2674
 
                    client["encrypted_secret"],
2675
 
                    client_settings[client_name]["secret"])
 
2478
                client["secret"] = (
 
2479
                    pgp.decrypt(client["encrypted_secret"],
 
2480
                                client_settings[client_name]
 
2481
                                ["secret"]))
2676
2482
            except PGPError:
2677
2483
                # If decryption fails, we use secret from new settings
2678
 
                logger.debug("Failed to decrypt {} old secret".format(
2679
 
                    client_name))
2680
 
                client["secret"] = (client_settings[client_name]
2681
 
                                    ["secret"])
 
2484
                logger.debug("Failed to decrypt {0} old secret"
 
2485
                             .format(client_name))
 
2486
                client["secret"] = (
 
2487
                    client_settings[client_name]["secret"])
2682
2488
    
2683
2489
    # Add/remove clients based on new changes made to config
2684
2490
    for client_name in (set(old_client_settings)
2689
2495
        clients_data[client_name] = client_settings[client_name]
2690
2496
    
2691
2497
    # Create all client objects
2692
 
    for client_name, client in clients_data.items():
 
2498
    for client_name, client in clients_data.iteritems():
2693
2499
        tcp_server.clients[client_name] = client_class(
2694
 
            name = client_name,
2695
 
            settings = client,
2696
 
            server_settings = server_settings)
 
2500
            name = client_name, settings = client)
2697
2501
    
2698
2502
    if not tcp_server.clients:
2699
2503
        logger.warning("No clients defined")
2703
2507
            try:
2704
2508
                with pidfile:
2705
2509
                    pid = os.getpid()
2706
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2510
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2707
2511
            except IOError:
2708
2512
                logger.error("Could not write to file %r with PID %d",
2709
2513
                             pidfilename, pid)
2714
2518
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2715
2519
    
2716
2520
    if use_dbus:
2717
 
        
2718
 
        @alternate_dbus_interfaces(
2719
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2521
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2522
                                        "se.bsnet.fukt.Mandos"})
2720
2523
        class MandosDBusService(DBusObjectWithProperties):
2721
2524
            """A D-Bus proxy object"""
2722
 
            
2723
2525
            def __init__(self):
2724
2526
                dbus.service.Object.__init__(self, bus, "/")
2725
 
            
2726
2527
            _interface = "se.recompile.Mandos"
2727
2528
            
2728
2529
            @dbus_interface_annotations(_interface)
2729
2530
            def _foo(self):
2730
 
                return {
2731
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2732
 
                    "false" }
 
2531
                return { "org.freedesktop.DBus.Property"
 
2532
                         ".EmitsChangedSignal":
 
2533
                             "false"}
2733
2534
            
2734
2535
            @dbus.service.signal(_interface, signature="o")
2735
2536
            def ClientAdded(self, objpath):
2749
2550
            @dbus.service.method(_interface, out_signature="ao")
2750
2551
            def GetAllClients(self):
2751
2552
                "D-Bus method"
2752
 
                return dbus.Array(c.dbus_object_path for c in
 
2553
                return dbus.Array(c.dbus_object_path
 
2554
                                  for c in
2753
2555
                                  tcp_server.clients.itervalues())
2754
2556
            
2755
2557
            @dbus.service.method(_interface,
2757
2559
            def GetAllClientsWithProperties(self):
2758
2560
                "D-Bus method"
2759
2561
                return dbus.Dictionary(
2760
 
                    { c.dbus_object_path: c.GetAll("")
2761
 
                      for c in tcp_server.clients.itervalues() },
 
2562
                    ((c.dbus_object_path, c.GetAll(""))
 
2563
                     for c in tcp_server.clients.itervalues()),
2762
2564
                    signature="oa{sv}")
2763
2565
            
2764
2566
            @dbus.service.method(_interface, in_signature="o")
2781
2583
    
2782
2584
    def cleanup():
2783
2585
        "Cleanup function; run on exit"
2784
 
        if zeroconf:
2785
 
            service.cleanup()
 
2586
        service.cleanup()
2786
2587
        
2787
2588
        multiprocessing.active_children()
2788
 
        wnull.close()
2789
2589
        if not (tcp_server.clients or client_settings):
2790
2590
            return
2791
2591
        
2802
2602
                
2803
2603
                # A list of attributes that can not be pickled
2804
2604
                # + secret.
2805
 
                exclude = { "bus", "changedstate", "secret",
2806
 
                            "checker", "server_settings" }
2807
 
                for name, typ in inspect.getmembers(dbus.service
2808
 
                                                    .Object):
 
2605
                exclude = set(("bus", "changedstate", "secret",
 
2606
                               "checker"))
 
2607
                for name, typ in (inspect.getmembers
 
2608
                                  (dbus.service.Object)):
2809
2609
                    exclude.add(name)
2810
2610
                
2811
2611
                client_dict["encrypted_secret"] = (client
2818
2618
                del client_settings[client.name]["secret"]
2819
2619
        
2820
2620
        try:
2821
 
            with tempfile.NamedTemporaryFile(
2822
 
                    mode='wb',
2823
 
                    suffix=".pickle",
2824
 
                    prefix='clients-',
2825
 
                    dir=os.path.dirname(stored_state_path),
2826
 
                    delete=False) as stored_state:
 
2621
            with (tempfile.NamedTemporaryFile
 
2622
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2623
                   dir=os.path.dirname(stored_state_path),
 
2624
                   delete=False)) as stored_state:
2827
2625
                pickle.dump((clients, client_settings), stored_state)
2828
 
                tempname = stored_state.name
 
2626
                tempname=stored_state.name
2829
2627
            os.rename(tempname, stored_state_path)
2830
2628
        except (IOError, OSError) as e:
2831
2629
            if not debug:
2834
2632
                except NameError:
2835
2633
                    pass
2836
2634
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2837
 
                logger.warning("Could not save persistent state: {}"
 
2635
                logger.warning("Could not save persistent state: {0}"
2838
2636
                               .format(os.strerror(e.errno)))
2839
2637
            else:
2840
2638
                logger.warning("Could not save persistent state:",
2841
2639
                               exc_info=e)
2842
 
                raise
 
2640
                raise e
2843
2641
        
2844
2642
        # Delete all clients, and settings from config
2845
2643
        while tcp_server.clients:
2850
2648
            client.disable(quiet=True)
2851
2649
            if use_dbus:
2852
2650
                # Emit D-Bus signal
2853
 
                mandos_dbus_service.ClientRemoved(
2854
 
                    client.dbus_object_path, client.name)
 
2651
                mandos_dbus_service.ClientRemoved(client
 
2652
                                                  .dbus_object_path,
 
2653
                                                  client.name)
2855
2654
        client_settings.clear()
2856
2655
    
2857
2656
    atexit.register(cleanup)
2868
2667
    tcp_server.server_activate()
2869
2668
    
2870
2669
    # Find out what port we got
2871
 
    if zeroconf:
2872
 
        service.port = tcp_server.socket.getsockname()[1]
 
2670
    service.port = tcp_server.socket.getsockname()[1]
2873
2671
    if use_ipv6:
2874
2672
        logger.info("Now listening on address %r, port %d,"
2875
2673
                    " flowinfo %d, scope_id %d",
2881
2679
    #service.interface = tcp_server.socket.getsockname()[3]
2882
2680
    
2883
2681
    try:
2884
 
        if zeroconf:
2885
 
            # From the Avahi example code
2886
 
            try:
2887
 
                service.activate()
2888
 
            except dbus.exceptions.DBusException as error:
2889
 
                logger.critical("D-Bus Exception", exc_info=error)
2890
 
                cleanup()
2891
 
                sys.exit(1)
2892
 
            # End of Avahi example code
 
2682
        # From the Avahi example code
 
2683
        try:
 
2684
            service.activate()
 
2685
        except dbus.exceptions.DBusException as error:
 
2686
            logger.critical("D-Bus Exception", exc_info=error)
 
2687
            cleanup()
 
2688
            sys.exit(1)
 
2689
        # End of Avahi example code
2893
2690
        
2894
2691
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2895
2692
                             lambda *args, **kwargs:
2910
2707
    # Must run before the D-Bus bus name gets deregistered
2911
2708
    cleanup()
2912
2709
 
2913
 
 
2914
2710
if __name__ == '__main__':
2915
2711
    main()