/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2015-07-06 20:09:47 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150706200947-w21u4eq74efgl6r5
Fix minor bugs and typos and add some more debug output.

* Makefile (install-client-nokey): Create plugin-helpers directory and
                                   the mandos-client-iprouteadddel
                                   helper program.
* initramfs-tools-hook (PLUGINHELPERDIR): Fix typo.
* plugins.d/mandos-client.c: Change terminology; routes are "deleted",
                             not "removed".  All occurences changed.
  (add_remove_local_route): Renamed to "add_delete_local_route".  All
                            callers changed.  Also pass "--debug" flag
                            to helper if in debug mode.
  (add_local_route): Add debugging output.
  (remove_local_route): Renamed to "delete_local_route".  All callers
                        changed.  Also pass "--debug" flag to helper
                        if in debug mode.
  (start_mandos_communication): Add debug output when adding route.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 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
36
36
 
37
37
from future_builtins import *
38
38
 
39
 
try:
40
 
    import SocketServer as socketserver
41
 
except ImportError:
42
 
    import socketserver
 
39
import SocketServer as socketserver
43
40
import socket
44
41
import argparse
45
42
import datetime
50
47
import gnutls.library.functions
51
48
import gnutls.library.constants
52
49
import gnutls.library.types
53
 
try:
54
 
    import ConfigParser as configparser
55
 
except ImportError:
56
 
    import configparser
 
50
import ConfigParser as configparser
57
51
import sys
58
52
import re
59
53
import os
68
62
import struct
69
63
import fcntl
70
64
import functools
71
 
try:
72
 
    import cPickle as pickle
73
 
except ImportError:
74
 
    import pickle
 
65
import cPickle as pickle
75
66
import multiprocessing
76
67
import types
77
68
import binascii
78
69
import tempfile
79
70
import itertools
80
71
import collections
81
 
import codecs
82
72
 
83
73
import dbus
84
74
import dbus.service
85
 
try:
86
 
    import gobject
87
 
except ImportError:
88
 
    from gi.repository import GObject as gobject
 
75
import gobject
89
76
import avahi
90
77
from dbus.mainloop.glib import DBusGMainLoop
91
78
import ctypes
111
98
syslogger = None
112
99
 
113
100
try:
114
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
115
 
        ctypes.util.find_library("c")).if_nametoindex
 
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
102
                      (ctypes.util.find_library("c"))
 
103
                      .if_nametoindex)
116
104
except (OSError, AttributeError):
117
 
    
118
105
    def if_nametoindex(interface):
119
106
        "Get an interface index the hard way, i.e. using fcntl()"
120
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
129
116
    """init logger and add loglevel"""
130
117
    
131
118
    global syslogger
132
 
    syslogger = (logging.handlers.SysLogHandler(
133
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
134
 
        address = "/dev/log"))
 
119
    syslogger = (logging.handlers.SysLogHandler
 
120
                 (facility =
 
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
122
                  address = "/dev/log"))
135
123
    syslogger.setFormatter(logging.Formatter
136
124
                           ('Mandos [%(process)d]: %(levelname)s:'
137
125
                            ' %(message)s'))
154
142
 
155
143
class PGPEngine(object):
156
144
    """A simple class for OpenPGP symmetric encryption & decryption"""
157
 
    
158
145
    def __init__(self):
159
146
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
160
147
        self.gnupgargs = ['--batch',
199
186
    
200
187
    def encrypt(self, data, password):
201
188
        passphrase = self.password_encode(password)
202
 
        with tempfile.NamedTemporaryFile(
203
 
                dir=self.tempdir) as passfile:
 
189
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
190
                                         ) as passfile:
204
191
            passfile.write(passphrase)
205
192
            passfile.flush()
206
193
            proc = subprocess.Popen(['gpg', '--symmetric',
217
204
    
218
205
    def decrypt(self, data, password):
219
206
        passphrase = self.password_encode(password)
220
 
        with tempfile.NamedTemporaryFile(
221
 
                dir = self.tempdir) as passfile:
 
207
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
208
                                         ) as passfile:
222
209
            passfile.write(passphrase)
223
210
            passfile.flush()
224
211
            proc = subprocess.Popen(['gpg', '--decrypt',
228
215
                                    stdin = subprocess.PIPE,
229
216
                                    stdout = subprocess.PIPE,
230
217
                                    stderr = subprocess.PIPE)
231
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
218
            decrypted_plaintext, err = proc.communicate(input
 
219
                                                        = data)
232
220
        if proc.returncode != 0:
233
221
            raise PGPError(err)
234
222
        return decrypted_plaintext
240
228
        return super(AvahiError, self).__init__(value, *args,
241
229
                                                **kwargs)
242
230
 
243
 
 
244
231
class AvahiServiceError(AvahiError):
245
232
    pass
246
233
 
247
 
 
248
234
class AvahiGroupError(AvahiError):
249
235
    pass
250
236
 
270
256
    bus: dbus.SystemBus()
271
257
    """
272
258
    
273
 
    def __init__(self,
274
 
                 interface = avahi.IF_UNSPEC,
275
 
                 name = None,
276
 
                 servicetype = None,
277
 
                 port = None,
278
 
                 TXT = None,
279
 
                 domain = "",
280
 
                 host = "",
281
 
                 max_renames = 32768,
282
 
                 protocol = avahi.PROTO_UNSPEC,
283
 
                 bus = None):
 
259
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
260
                 servicetype = None, port = None, TXT = None,
 
261
                 domain = "", host = "", max_renames = 32768,
 
262
                 protocol = avahi.PROTO_UNSPEC, bus = None):
284
263
        self.interface = interface
285
264
        self.name = name
286
265
        self.type = servicetype
303
282
                            " after %i retries, exiting.",
304
283
                            self.rename_count)
305
284
            raise AvahiServiceError("Too many renames")
306
 
        self.name = str(
307
 
            self.server.GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
308
287
        self.rename_count += 1
309
288
        logger.info("Changing Zeroconf service name to %r ...",
310
289
                    self.name)
365
344
        elif state == avahi.ENTRY_GROUP_FAILURE:
366
345
            logger.critical("Avahi: Error in group state changed %s",
367
346
                            str(error))
368
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
347
            raise AvahiGroupError("State changed: {!s}"
 
348
                                  .format(error))
369
349
    
370
350
    def cleanup(self):
371
351
        """Derived from the Avahi example code"""
381
361
    def server_state_changed(self, state, error=None):
382
362
        """Derived from the Avahi example code"""
383
363
        logger.debug("Avahi server state change: %i", state)
384
 
        bad_states = {
385
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
386
 
            avahi.SERVER_REGISTERING: None,
387
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
388
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
389
 
        }
 
364
        bad_states = { avahi.SERVER_INVALID:
 
365
                           "Zeroconf server invalid",
 
366
                       avahi.SERVER_REGISTERING: None,
 
367
                       avahi.SERVER_COLLISION:
 
368
                           "Zeroconf server name collision",
 
369
                       avahi.SERVER_FAILURE:
 
370
                           "Zeroconf server failure" }
390
371
        if state in bad_states:
391
372
            if bad_states[state] is not None:
392
373
                if error is None:
411
392
                                    follow_name_owner_changes=True),
412
393
                avahi.DBUS_INTERFACE_SERVER)
413
394
        self.server.connect_to_signal("StateChanged",
414
 
                                      self.server_state_changed)
 
395
                                 self.server_state_changed)
415
396
        self.server_state_changed(self.server.GetState())
416
397
 
417
398
 
419
400
    def rename(self, *args, **kwargs):
420
401
        """Add the new name to the syslog messages"""
421
402
        ret = AvahiService.rename(self, *args, **kwargs)
422
 
        syslogger.setFormatter(logging.Formatter(
423
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
424
 
            .format(self.name)))
 
403
        syslogger.setFormatter(logging.Formatter
 
404
                               ('Mandos ({}) [%(process)d]:'
 
405
                                ' %(levelname)s: %(message)s'
 
406
                                .format(self.name)))
425
407
        return ret
426
408
 
427
 
def call_pipe(connection,       # : multiprocessing.Connection
428
 
              func, *args, **kwargs):
429
 
    """This function is meant to be called by multiprocessing.Process
430
 
    
431
 
    This function runs func(*args, **kwargs), and writes the resulting
432
 
    return value on the provided multiprocessing.Connection.
433
 
    """
434
 
    connection.send(func(*args, **kwargs))
435
 
    connection.close()
436
409
 
437
410
class Client(object):
438
411
    """A representation of a client host served by this server.
465
438
    last_checker_status: integer between 0 and 255 reflecting exit
466
439
                         status of last checker. -1 reflects crashed
467
440
                         checker, -2 means no checker completed yet.
468
 
    last_checker_signal: The signal which killed the last checker, if
469
 
                         last_checker_status is -1
470
441
    last_enabled: datetime.datetime(); (UTC) or None
471
442
    name:       string; from the config file, used in log messages and
472
443
                        D-Bus identifiers
485
456
                          "fingerprint", "host", "interval",
486
457
                          "last_approval_request", "last_checked_ok",
487
458
                          "last_enabled", "name", "timeout")
488
 
    client_defaults = {
489
 
        "timeout": "PT5M",
490
 
        "extended_timeout": "PT15M",
491
 
        "interval": "PT2M",
492
 
        "checker": "fping -q -- %%(host)s",
493
 
        "host": "",
494
 
        "approval_delay": "PT0S",
495
 
        "approval_duration": "PT1S",
496
 
        "approved_by_default": "True",
497
 
        "enabled": "True",
498
 
    }
 
459
    client_defaults = { "timeout": "PT5M",
 
460
                        "extended_timeout": "PT15M",
 
461
                        "interval": "PT2M",
 
462
                        "checker": "fping -q -- %%(host)s",
 
463
                        "host": "",
 
464
                        "approval_delay": "PT0S",
 
465
                        "approval_duration": "PT1S",
 
466
                        "approved_by_default": "True",
 
467
                        "enabled": "True",
 
468
                        }
499
469
    
500
470
    @staticmethod
501
471
    def config_parser(config):
517
487
            client["enabled"] = config.getboolean(client_name,
518
488
                                                  "enabled")
519
489
            
520
 
            # Uppercase and remove spaces from fingerprint for later
521
 
            # comparison purposes with return value from the
522
 
            # fingerprint() function
523
490
            client["fingerprint"] = (section["fingerprint"].upper()
524
491
                                     .replace(" ", ""))
525
492
            if "secret" in section:
567
534
            self.expires = None
568
535
        
569
536
        logger.debug("Creating client %r", self.name)
 
537
        # Uppercase and remove spaces from fingerprint for later
 
538
        # comparison purposes with return value from the fingerprint()
 
539
        # function
570
540
        logger.debug("  Fingerprint: %s", self.fingerprint)
571
541
        self.created = settings.get("created",
572
542
                                    datetime.datetime.utcnow())
579
549
        self.current_checker_command = None
580
550
        self.approved = None
581
551
        self.approvals_pending = 0
582
 
        self.changedstate = multiprocessing_manager.Condition(
583
 
            multiprocessing_manager.Lock())
584
 
        self.client_structure = [attr
585
 
                                 for attr in self.__dict__.iterkeys()
 
552
        self.changedstate = (multiprocessing_manager
 
553
                             .Condition(multiprocessing_manager
 
554
                                        .Lock()))
 
555
        self.client_structure = [attr for attr in
 
556
                                 self.__dict__.iterkeys()
586
557
                                 if not attr.startswith("_")]
587
558
        self.client_structure.append("client_structure")
588
559
        
589
 
        for name, t in inspect.getmembers(
590
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
591
564
            if not name.startswith("_"):
592
565
                self.client_structure.append(name)
593
566
    
635
608
        # and every interval from then on.
636
609
        if self.checker_initiator_tag is not None:
637
610
            gobject.source_remove(self.checker_initiator_tag)
638
 
        self.checker_initiator_tag = gobject.timeout_add(
639
 
            int(self.interval.total_seconds() * 1000),
640
 
            self.start_checker)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
641
615
        # Schedule a disable() when 'timeout' has passed
642
616
        if self.disable_initiator_tag is not None:
643
617
            gobject.source_remove(self.disable_initiator_tag)
644
 
        self.disable_initiator_tag = gobject.timeout_add(
645
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
618
        self.disable_initiator_tag = (gobject.timeout_add
 
619
                                      (int(self.timeout
 
620
                                           .total_seconds() * 1000),
 
621
                                       self.disable))
646
622
        # Also start a new checker *right now*.
647
623
        self.start_checker()
648
624
    
649
 
    def checker_callback(self, source, condition, connection,
650
 
                         command):
 
625
    def checker_callback(self, pid, condition, command):
651
626
        """The checker has completed, so take appropriate actions."""
652
627
        self.checker_callback_tag = None
653
628
        self.checker = None
654
 
        # Read return code from connection (see call_pipe)
655
 
        returncode = connection.recv()
656
 
        connection.close()
657
 
        
658
 
        if returncode >= 0:
659
 
            self.last_checker_status = returncode
660
 
            self.last_checker_signal = None
 
629
        if os.WIFEXITED(condition):
 
630
            self.last_checker_status = os.WEXITSTATUS(condition)
661
631
            if self.last_checker_status == 0:
662
632
                logger.info("Checker for %(name)s succeeded",
663
633
                            vars(self))
664
634
                self.checked_ok()
665
635
            else:
666
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
667
638
        else:
668
639
            self.last_checker_status = -1
669
 
            self.last_checker_signal = -returncode
670
640
            logger.warning("Checker for %(name)s crashed?",
671
641
                           vars(self))
672
 
        return False
673
642
    
674
643
    def checked_ok(self):
675
644
        """Assert that the client has been seen, alive and well."""
676
645
        self.last_checked_ok = datetime.datetime.utcnow()
677
646
        self.last_checker_status = 0
678
 
        self.last_checker_signal = None
679
647
        self.bump_timeout()
680
648
    
681
649
    def bump_timeout(self, timeout=None):
686
654
            gobject.source_remove(self.disable_initiator_tag)
687
655
            self.disable_initiator_tag = None
688
656
        if getattr(self, "enabled", False):
689
 
            self.disable_initiator_tag = gobject.timeout_add(
690
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
691
660
            self.expires = datetime.datetime.utcnow() + timeout
692
661
    
693
662
    def need_approval(self):
707
676
        # than 'timeout' for the client to be disabled, which is as it
708
677
        # should be.
709
678
        
710
 
        if self.checker is not None and not self.checker.is_alive():
711
 
            logger.warning("Checker was not alive; joining")
712
 
            self.checker.join()
713
 
            self.checker = None
 
679
        # If a checker exists, make sure it is not a zombie
 
680
        try:
 
681
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
682
        except AttributeError:
 
683
            pass
 
684
        except OSError as error:
 
685
            if error.errno != errno.ECHILD:
 
686
                raise
 
687
        else:
 
688
            if pid:
 
689
                logger.warning("Checker was a zombie")
 
690
                gobject.source_remove(self.checker_callback_tag)
 
691
                self.checker_callback(pid, status,
 
692
                                      self.current_checker_command)
714
693
        # Start a new checker if needed
715
694
        if self.checker is None:
716
695
            # Escape attributes for the shell
717
 
            escaped_attrs = {
718
 
                attr: re.escape(str(getattr(self, attr)))
719
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
720
699
            try:
721
700
                command = self.checker_command % escaped_attrs
722
701
            except TypeError as error:
723
702
                logger.error('Could not format string "%s"',
724
 
                             self.checker_command,
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
 
705
            self.current_checker_command = command
 
706
            try:
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
 
709
                # We don't need to redirect stdout and stderr, since
 
710
                # in normal mode, that is already done by daemon(),
 
711
                # and in debug mode we don't want to.  (Stdin is
 
712
                # always replaced by /dev/null.)
 
713
                # The exception is when not debugging but nevertheless
 
714
                # running in the foreground; use the previously
 
715
                # created wnull.
 
716
                popen_args = {}
 
717
                if (not self.server_settings["debug"]
 
718
                    and self.server_settings["foreground"]):
 
719
                    popen_args.update({"stdout": wnull,
 
720
                                       "stderr": wnull })
 
721
                self.checker = subprocess.Popen(command,
 
722
                                                close_fds=True,
 
723
                                                shell=True, cwd="/",
 
724
                                                **popen_args)
 
725
            except OSError as error:
 
726
                logger.error("Failed to start subprocess",
725
727
                             exc_info=error)
726
 
                return True     # Try again later
727
 
            self.current_checker_command = command
728
 
            logger.info("Starting checker %r for %s", command,
729
 
                        self.name)
730
 
            # We don't need to redirect stdout and stderr, since
731
 
            # in normal mode, that is already done by daemon(),
732
 
            # and in debug mode we don't want to.  (Stdin is
733
 
            # always replaced by /dev/null.)
734
 
            # The exception is when not debugging but nevertheless
735
 
            # running in the foreground; use the previously
736
 
            # created wnull.
737
 
            popen_args = { "close_fds": True,
738
 
                           "shell": True,
739
 
                           "cwd": "/" }
740
 
            if (not self.server_settings["debug"]
741
 
                and self.server_settings["foreground"]):
742
 
                popen_args.update({"stdout": wnull,
743
 
                                   "stderr": wnull })
744
 
            pipe = multiprocessing.Pipe(duplex = False)
745
 
            self.checker = multiprocessing.Process(
746
 
                target = call_pipe,
747
 
                args = (pipe[1], subprocess.call, command),
748
 
                kwargs = popen_args)
749
 
            self.checker.start()
750
 
            self.checker_callback_tag = gobject.io_add_watch(
751
 
                pipe[0].fileno(), gobject.IO_IN,
752
 
                self.checker_callback, pipe[0], command)
 
728
                return True
 
729
            self.checker_callback_tag = (gobject.child_watch_add
 
730
                                         (self.checker.pid,
 
731
                                          self.checker_callback,
 
732
                                          data=command))
 
733
            # The checker may have completed before the gobject
 
734
            # watch was added.  Check for this.
 
735
            try:
 
736
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
737
            except OSError as error:
 
738
                if error.errno == errno.ECHILD:
 
739
                    # This should never happen
 
740
                    logger.error("Child process vanished",
 
741
                                 exc_info=error)
 
742
                    return True
 
743
                raise
 
744
            if pid:
 
745
                gobject.source_remove(self.checker_callback_tag)
 
746
                self.checker_callback(pid, status, command)
753
747
        # Re-run this periodically if run by gobject.timeout_add
754
748
        return True
755
749
    
761
755
        if getattr(self, "checker", None) is None:
762
756
            return
763
757
        logger.debug("Stopping checker for %(name)s", vars(self))
764
 
        self.checker.terminate()
 
758
        try:
 
759
            self.checker.terminate()
 
760
            #time.sleep(0.5)
 
761
            #if self.checker.poll() is None:
 
762
            #    self.checker.kill()
 
763
        except OSError as error:
 
764
            if error.errno != errno.ESRCH: # No such process
 
765
                raise
765
766
        self.checker = None
766
767
 
767
768
 
768
 
def dbus_service_property(dbus_interface,
769
 
                          signature="v",
770
 
                          access="readwrite",
771
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
772
771
    """Decorators for marking methods of a DBusObjectWithProperties to
773
772
    become properties on the D-Bus.
774
773
    
784
783
    if byte_arrays and signature != "ay":
785
784
        raise ValueError("Byte arrays not supported for non-'ay'"
786
785
                         " signature {!r}".format(signature))
787
 
    
788
786
    def decorator(func):
789
787
        func._dbus_is_property = True
790
788
        func._dbus_interface = dbus_interface
795
793
            func._dbus_name = func._dbus_name[:-14]
796
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
797
795
        return func
798
 
    
799
796
    return decorator
800
797
 
801
798
 
810
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
811
808
                    "false"}
812
809
    """
813
 
    
814
810
    def decorator(func):
815
811
        func._dbus_is_interface = True
816
812
        func._dbus_interface = dbus_interface
817
813
        func._dbus_name = dbus_interface
818
814
        return func
819
 
    
820
815
    return decorator
821
816
 
822
817
 
832
827
    def Property_dbus_property(self):
833
828
        return dbus.Boolean(False)
834
829
    """
835
 
    
836
830
    def decorator(func):
837
831
        func._dbus_annotations = annotations
838
832
        return func
839
 
    
840
833
    return decorator
841
834
 
842
835
 
845
838
    """
846
839
    pass
847
840
 
848
 
 
849
841
class DBusPropertyAccessException(DBusPropertyException):
850
842
    """A property's access permissions disallows an operation.
851
843
    """
879
871
    def _get_all_dbus_things(self, thing):
880
872
        """Returns a generator of (name, attribute) pairs
881
873
        """
882
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
883
876
                 athing.__get__(self))
884
877
                for cls in self.__class__.__mro__
885
878
                for name, athing in
886
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
887
881
    
888
882
    def _get_dbus_property(self, interface_name, property_name):
889
883
        """Returns a bound method if one exists which is a D-Bus
890
884
        property with the specified name and interface.
891
885
        """
892
 
        for cls in self.__class__.__mro__:
893
 
            for name, value in inspect.getmembers(
894
 
                    cls, self._is_dbus_thing("property")):
 
886
        for cls in  self.__class__.__mro__:
 
887
            for name, value in (inspect.getmembers
 
888
                                (cls,
 
889
                                 self._is_dbus_thing("property"))):
895
890
                if (value._dbus_name == property_name
896
891
                    and value._dbus_interface == interface_name):
897
892
                    return value.__get__(self)
898
893
        
899
894
        # No such property
900
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
901
 
            self.dbus_object_path, interface_name, property_name))
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
902
898
    
903
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
904
 
                         in_signature="ss",
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
905
900
                         out_signature="v")
906
901
    def Get(self, interface_name, property_name):
907
902
        """Standard D-Bus property Get() method, see D-Bus standard.
932
927
                                            for byte in value))
933
928
        prop(value)
934
929
    
935
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
936
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
937
931
                         out_signature="a{sv}")
938
932
    def GetAll(self, interface_name):
939
933
        """Standard D-Bus property GetAll() method, see D-Bus
954
948
            if not hasattr(value, "variant_level"):
955
949
                properties[name] = value
956
950
                continue
957
 
            properties[name] = type(value)(
958
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
959
953
        return dbus.Dictionary(properties, signature="sv")
960
954
    
961
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
979
973
                                                   connection)
980
974
        try:
981
975
            document = xml.dom.minidom.parseString(xmlstring)
982
 
            
983
976
            def make_tag(document, name, prop):
984
977
                e = document.createElement("property")
985
978
                e.setAttribute("name", name)
986
979
                e.setAttribute("type", prop._dbus_signature)
987
980
                e.setAttribute("access", prop._dbus_access)
988
981
                return e
989
 
            
990
982
            for if_tag in document.getElementsByTagName("interface"):
991
983
                # Add property tags
992
984
                for tag in (make_tag(document, name, prop)
1004
996
                            if (name == tag.getAttribute("name")
1005
997
                                and prop._dbus_interface
1006
998
                                == if_tag.getAttribute("name")):
1007
 
                                annots.update(getattr(
1008
 
                                    prop, "_dbus_annotations", {}))
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
1009
1003
                        for name, value in annots.items():
1010
1004
                            ann_tag = document.createElement(
1011
1005
                                "annotation")
1016
1010
                for annotation, value in dict(
1017
1011
                    itertools.chain.from_iterable(
1018
1012
                        annotations().items()
1019
 
                        for name, annotations
1020
 
                        in self._get_all_dbus_things("interface")
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
1021
1015
                        if name == if_tag.getAttribute("name")
1022
1016
                        )).items():
1023
1017
                    ann_tag = document.createElement("annotation")
1052
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1053
1047
    if dt is None:
1054
1048
        return dbus.String("", variant_level = variant_level)
1055
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1056
1051
 
1057
1052
 
1058
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1078
1073
    (from DBusObjectWithProperties) and interfaces (from the
1079
1074
    dbus_interface_annotations decorator).
1080
1075
    """
1081
 
    
1082
1076
    def wrapper(cls):
1083
1077
        for orig_interface_name, alt_interface_name in (
1084
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1085
1079
            attr = {}
1086
1080
            interface_names = set()
1087
1081
            # Go though all attributes of the class
1089
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1090
1084
                # with the wrong interface name
1091
1085
                if (not hasattr(attribute, "_dbus_interface")
1092
 
                    or not attribute._dbus_interface.startswith(
1093
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1094
1088
                    continue
1095
1089
                # Create an alternate D-Bus interface name based on
1096
1090
                # the current name
1097
 
                alt_interface = attribute._dbus_interface.replace(
1098
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1099
1094
                interface_names.add(alt_interface)
1100
1095
                # Is this a D-Bus signal?
1101
1096
                if getattr(attribute, "_dbus_is_signal", False):
1102
 
                    if sys.version_info.major == 2:
1103
 
                        # Extract the original non-method undecorated
1104
 
                        # function by black magic
1105
 
                        nonmethod_func = (dict(
 
1097
                    # Extract the original non-method undecorated
 
1098
                    # function by black magic
 
1099
                    nonmethod_func = (dict(
1106
1100
                            zip(attribute.func_code.co_freevars,
1107
 
                                attribute.__closure__))
1108
 
                                          ["func"].cell_contents)
1109
 
                    else:
1110
 
                        nonmethod_func = attribute
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1111
1103
                    # Create a new, but exactly alike, function
1112
1104
                    # object, and decorate it to be a new D-Bus signal
1113
1105
                    # with the alternate D-Bus interface name
1114
 
                    if sys.version_info.major == 2:
1115
 
                        new_function = types.FunctionType(
1116
 
                            nonmethod_func.func_code,
1117
 
                            nonmethod_func.func_globals,
1118
 
                            nonmethod_func.func_name,
1119
 
                            nonmethod_func.func_defaults,
1120
 
                            nonmethod_func.func_closure)
1121
 
                    else:
1122
 
                        new_function = types.FunctionType(
1123
 
                            nonmethod_func.__code__,
1124
 
                            nonmethod_func.__globals__,
1125
 
                            nonmethod_func.__name__,
1126
 
                            nonmethod_func.__defaults__,
1127
 
                            nonmethod_func.__closure__)
1128
 
                    new_function = (dbus.service.signal(
1129
 
                        alt_interface,
1130
 
                        attribute._dbus_signature)(new_function))
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
 
1109
                                    (types.FunctionType(
 
1110
                                nonmethod_func.func_code,
 
1111
                                nonmethod_func.func_globals,
 
1112
                                nonmethod_func.func_name,
 
1113
                                nonmethod_func.func_defaults,
 
1114
                                nonmethod_func.func_closure)))
1131
1115
                    # Copy annotations, if any
1132
1116
                    try:
1133
 
                        new_function._dbus_annotations = dict(
1134
 
                            attribute._dbus_annotations)
 
1117
                        new_function._dbus_annotations = (
 
1118
                            dict(attribute._dbus_annotations))
1135
1119
                    except AttributeError:
1136
1120
                        pass
1137
1121
                    # Define a creator of a function to call both the
1142
1126
                        """This function is a scope container to pass
1143
1127
                        func1 and func2 to the "call_both" function
1144
1128
                        outside of its arguments"""
1145
 
                        
1146
1129
                        def call_both(*args, **kwargs):
1147
1130
                            """This function will emit two D-Bus
1148
1131
                            signals by calling func1 and func2"""
1149
1132
                            func1(*args, **kwargs)
1150
1133
                            func2(*args, **kwargs)
1151
 
                        
1152
1134
                        return call_both
1153
1135
                    # Create the "call_both" function and add it to
1154
1136
                    # the class
1159
1141
                    # object.  Decorate it to be a new D-Bus method
1160
1142
                    # with the alternate D-Bus interface name.  Add it
1161
1143
                    # to the class.
1162
 
                    attr[attrname] = (
1163
 
                        dbus.service.method(
1164
 
                            alt_interface,
1165
 
                            attribute._dbus_in_signature,
1166
 
                            attribute._dbus_out_signature)
1167
 
                        (types.FunctionType(attribute.func_code,
1168
 
                                            attribute.func_globals,
1169
 
                                            attribute.func_name,
1170
 
                                            attribute.func_defaults,
1171
 
                                            attribute.func_closure)))
 
1144
                    attr[attrname] = (dbus.service.method
 
1145
                                      (alt_interface,
 
1146
                                       attribute._dbus_in_signature,
 
1147
                                       attribute._dbus_out_signature)
 
1148
                                      (types.FunctionType
 
1149
                                       (attribute.func_code,
 
1150
                                        attribute.func_globals,
 
1151
                                        attribute.func_name,
 
1152
                                        attribute.func_defaults,
 
1153
                                        attribute.func_closure)))
1172
1154
                    # Copy annotations, if any
1173
1155
                    try:
1174
 
                        attr[attrname]._dbus_annotations = dict(
1175
 
                            attribute._dbus_annotations)
 
1156
                        attr[attrname]._dbus_annotations = (
 
1157
                            dict(attribute._dbus_annotations))
1176
1158
                    except AttributeError:
1177
1159
                        pass
1178
1160
                # Is this a D-Bus property?
1181
1163
                    # object, and decorate it to be a new D-Bus
1182
1164
                    # property with the alternate D-Bus interface
1183
1165
                    # name.  Add it to the class.
1184
 
                    attr[attrname] = (dbus_service_property(
1185
 
                        alt_interface, attribute._dbus_signature,
1186
 
                        attribute._dbus_access,
1187
 
                        attribute._dbus_get_args_options
1188
 
                        ["byte_arrays"])
1189
 
                                      (types.FunctionType(
1190
 
                                          attribute.func_code,
1191
 
                                          attribute.func_globals,
1192
 
                                          attribute.func_name,
1193
 
                                          attribute.func_defaults,
1194
 
                                          attribute.func_closure)))
 
1166
                    attr[attrname] = (dbus_service_property
 
1167
                                      (alt_interface,
 
1168
                                       attribute._dbus_signature,
 
1169
                                       attribute._dbus_access,
 
1170
                                       attribute
 
1171
                                       ._dbus_get_args_options
 
1172
                                       ["byte_arrays"])
 
1173
                                      (types.FunctionType
 
1174
                                       (attribute.func_code,
 
1175
                                        attribute.func_globals,
 
1176
                                        attribute.func_name,
 
1177
                                        attribute.func_defaults,
 
1178
                                        attribute.func_closure)))
1195
1179
                    # Copy annotations, if any
1196
1180
                    try:
1197
 
                        attr[attrname]._dbus_annotations = dict(
1198
 
                            attribute._dbus_annotations)
 
1181
                        attr[attrname]._dbus_annotations = (
 
1182
                            dict(attribute._dbus_annotations))
1199
1183
                    except AttributeError:
1200
1184
                        pass
1201
1185
                # Is this a D-Bus interface?
1204
1188
                    # object.  Decorate it to be a new D-Bus interface
1205
1189
                    # with the alternate D-Bus interface name.  Add it
1206
1190
                    # to the class.
1207
 
                    attr[attrname] = (
1208
 
                        dbus_interface_annotations(alt_interface)
1209
 
                        (types.FunctionType(attribute.func_code,
1210
 
                                            attribute.func_globals,
1211
 
                                            attribute.func_name,
1212
 
                                            attribute.func_defaults,
1213
 
                                            attribute.func_closure)))
 
1191
                    attr[attrname] = (dbus_interface_annotations
 
1192
                                      (alt_interface)
 
1193
                                      (types.FunctionType
 
1194
                                       (attribute.func_code,
 
1195
                                        attribute.func_globals,
 
1196
                                        attribute.func_name,
 
1197
                                        attribute.func_defaults,
 
1198
                                        attribute.func_closure)))
1214
1199
            if deprecate:
1215
1200
                # Deprecate all alternate interfaces
1216
1201
                iname="_AlternateDBusNames_interface_annotation{}"
1217
1202
                for interface_name in interface_names:
1218
 
                    
1219
1203
                    @dbus_interface_annotations(interface_name)
1220
1204
                    def func(self):
1221
1205
                        return { "org.freedesktop.DBus.Deprecated":
1222
 
                                 "true" }
 
1206
                                     "true" }
1223
1207
                    # Find an unused name
1224
1208
                    for aname in (iname.format(i)
1225
1209
                                  for i in itertools.count()):
1230
1214
                # Replace the class with a new subclass of it with
1231
1215
                # methods, signals, etc. as created above.
1232
1216
                cls = type(b"{}Alternate".format(cls.__name__),
1233
 
                           (cls, ), attr)
 
1217
                           (cls,), attr)
1234
1218
        return cls
1235
 
    
1236
1219
    return wrapper
1237
1220
 
1238
1221
 
1239
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1240
 
                            "se.bsnet.fukt.Mandos"})
 
1223
                                "se.bsnet.fukt.Mandos"})
1241
1224
class ClientDBus(Client, DBusObjectWithProperties):
1242
1225
    """A Client class using D-Bus
1243
1226
    
1247
1230
    """
1248
1231
    
1249
1232
    runtime_expansions = (Client.runtime_expansions
1250
 
                          + ("dbus_object_path", ))
 
1233
                          + ("dbus_object_path",))
1251
1234
    
1252
1235
    _interface = "se.recompile.Mandos.Client"
1253
1236
    
1261
1244
        client_object_name = str(self.name).translate(
1262
1245
            {ord("."): ord("_"),
1263
1246
             ord("-"): ord("_")})
1264
 
        self.dbus_object_path = dbus.ObjectPath(
1265
 
            "/clients/" + client_object_name)
 
1247
        self.dbus_object_path = (dbus.ObjectPath
 
1248
                                 ("/clients/" + client_object_name))
1266
1249
        DBusObjectWithProperties.__init__(self, self.bus,
1267
1250
                                          self.dbus_object_path)
1268
1251
    
1269
 
    def notifychangeproperty(transform_func, dbus_name,
1270
 
                             type_func=lambda x: x,
1271
 
                             variant_level=1,
1272
 
                             invalidate_only=False,
 
1252
    def notifychangeproperty(transform_func,
 
1253
                             dbus_name, type_func=lambda x: x,
 
1254
                             variant_level=1, invalidate_only=False,
1273
1255
                             _interface=_interface):
1274
1256
        """ Modify a variable so that it's a property which announces
1275
1257
        its changes to DBus.
1282
1264
        variant_level: D-Bus variant level.  Default: 1
1283
1265
        """
1284
1266
        attrname = "_{}".format(dbus_name)
1285
 
        
1286
1267
        def setter(self, value):
1287
1268
            if hasattr(self, "dbus_object_path"):
1288
1269
                if (not hasattr(self, attrname) or
1289
1270
                    type_func(getattr(self, attrname, None))
1290
1271
                    != type_func(value)):
1291
1272
                    if invalidate_only:
1292
 
                        self.PropertiesChanged(
1293
 
                            _interface, dbus.Dictionary(),
1294
 
                            dbus.Array((dbus_name, )))
 
1273
                        self.PropertiesChanged(_interface,
 
1274
                                               dbus.Dictionary(),
 
1275
                                               dbus.Array
 
1276
                                               ((dbus_name,)))
1295
1277
                    else:
1296
 
                        dbus_value = transform_func(
1297
 
                            type_func(value),
1298
 
                            variant_level = variant_level)
 
1278
                        dbus_value = transform_func(type_func(value),
 
1279
                                                    variant_level
 
1280
                                                    =variant_level)
1299
1281
                        self.PropertyChanged(dbus.String(dbus_name),
1300
1282
                                             dbus_value)
1301
 
                        self.PropertiesChanged(
1302
 
                            _interface,
1303
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1304
 
                                              dbus_value }),
1305
 
                            dbus.Array())
 
1283
                        self.PropertiesChanged(_interface,
 
1284
                                               dbus.Dictionary({
 
1285
                                    dbus.String(dbus_name):
 
1286
                                        dbus_value }), dbus.Array())
1306
1287
            setattr(self, attrname, value)
1307
1288
        
1308
1289
        return property(lambda self: getattr(self, attrname), setter)
1314
1295
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1315
1296
    last_enabled = notifychangeproperty(datetime_to_dbus,
1316
1297
                                        "LastEnabled")
1317
 
    checker = notifychangeproperty(
1318
 
        dbus.Boolean, "CheckerRunning",
1319
 
        type_func = lambda checker: checker is not None)
 
1298
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1299
                                   type_func = lambda checker:
 
1300
                                       checker is not None)
1320
1301
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1321
1302
                                           "LastCheckedOK")
1322
1303
    last_checker_status = notifychangeproperty(dbus.Int16,
1325
1306
        datetime_to_dbus, "LastApprovalRequest")
1326
1307
    approved_by_default = notifychangeproperty(dbus.Boolean,
1327
1308
                                               "ApprovedByDefault")
1328
 
    approval_delay = notifychangeproperty(
1329
 
        dbus.UInt64, "ApprovalDelay",
1330
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1309
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1310
                                          "ApprovalDelay",
 
1311
                                          type_func =
 
1312
                                          lambda td: td.total_seconds()
 
1313
                                          * 1000)
1331
1314
    approval_duration = notifychangeproperty(
1332
1315
        dbus.UInt64, "ApprovalDuration",
1333
1316
        type_func = lambda td: td.total_seconds() * 1000)
1334
1317
    host = notifychangeproperty(dbus.String, "Host")
1335
 
    timeout = notifychangeproperty(
1336
 
        dbus.UInt64, "Timeout",
1337
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1318
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1319
                                   type_func = lambda td:
 
1320
                                       td.total_seconds() * 1000)
1338
1321
    extended_timeout = notifychangeproperty(
1339
1322
        dbus.UInt64, "ExtendedTimeout",
1340
1323
        type_func = lambda td: td.total_seconds() * 1000)
1341
 
    interval = notifychangeproperty(
1342
 
        dbus.UInt64, "Interval",
1343
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1324
    interval = notifychangeproperty(dbus.UInt64,
 
1325
                                    "Interval",
 
1326
                                    type_func =
 
1327
                                    lambda td: td.total_seconds()
 
1328
                                    * 1000)
1344
1329
    checker_command = notifychangeproperty(dbus.String, "Checker")
1345
1330
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1346
1331
                                  invalidate_only=True)
1356
1341
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1357
1342
        Client.__del__(self, *args, **kwargs)
1358
1343
    
1359
 
    def checker_callback(self, source, condition,
1360
 
                         connection, command, *args, **kwargs):
1361
 
        ret = Client.checker_callback(self, source, condition,
1362
 
                                      connection, command, *args,
1363
 
                                      **kwargs)
1364
 
        exitstatus = self.last_checker_status
1365
 
        if exitstatus >= 0:
 
1344
    def checker_callback(self, pid, condition, command,
 
1345
                         *args, **kwargs):
 
1346
        self.checker_callback_tag = None
 
1347
        self.checker = None
 
1348
        if os.WIFEXITED(condition):
 
1349
            exitstatus = os.WEXITSTATUS(condition)
1366
1350
            # Emit D-Bus signal
1367
1351
            self.CheckerCompleted(dbus.Int16(exitstatus),
1368
 
                                  dbus.Int64(0),
 
1352
                                  dbus.Int64(condition),
1369
1353
                                  dbus.String(command))
1370
1354
        else:
1371
1355
            # Emit D-Bus signal
1372
1356
            self.CheckerCompleted(dbus.Int16(-1),
1373
 
                                  dbus.Int64(
1374
 
                                      self.last_checker_signal),
 
1357
                                  dbus.Int64(condition),
1375
1358
                                  dbus.String(command))
1376
 
        return ret
 
1359
        
 
1360
        return Client.checker_callback(self, pid, condition, command,
 
1361
                                       *args, **kwargs)
1377
1362
    
1378
1363
    def start_checker(self, *args, **kwargs):
1379
1364
        old_checker_pid = getattr(self.checker, "pid", None)
1484
1469
        return dbus.Boolean(bool(self.approvals_pending))
1485
1470
    
1486
1471
    # ApprovedByDefault - property
1487
 
    @dbus_service_property(_interface,
1488
 
                           signature="b",
 
1472
    @dbus_service_property(_interface, signature="b",
1489
1473
                           access="readwrite")
1490
1474
    def ApprovedByDefault_dbus_property(self, value=None):
1491
1475
        if value is None:       # get
1493
1477
        self.approved_by_default = bool(value)
1494
1478
    
1495
1479
    # ApprovalDelay - property
1496
 
    @dbus_service_property(_interface,
1497
 
                           signature="t",
 
1480
    @dbus_service_property(_interface, signature="t",
1498
1481
                           access="readwrite")
1499
1482
    def ApprovalDelay_dbus_property(self, value=None):
1500
1483
        if value is None:       # get
1503
1486
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1504
1487
    
1505
1488
    # ApprovalDuration - property
1506
 
    @dbus_service_property(_interface,
1507
 
                           signature="t",
 
1489
    @dbus_service_property(_interface, signature="t",
1508
1490
                           access="readwrite")
1509
1491
    def ApprovalDuration_dbus_property(self, value=None):
1510
1492
        if value is None:       # get
1523
1505
        return dbus.String(self.fingerprint)
1524
1506
    
1525
1507
    # Host - property
1526
 
    @dbus_service_property(_interface,
1527
 
                           signature="s",
 
1508
    @dbus_service_property(_interface, signature="s",
1528
1509
                           access="readwrite")
1529
1510
    def Host_dbus_property(self, value=None):
1530
1511
        if value is None:       # get
1542
1523
        return datetime_to_dbus(self.last_enabled)
1543
1524
    
1544
1525
    # Enabled - property
1545
 
    @dbus_service_property(_interface,
1546
 
                           signature="b",
 
1526
    @dbus_service_property(_interface, signature="b",
1547
1527
                           access="readwrite")
1548
1528
    def Enabled_dbus_property(self, value=None):
1549
1529
        if value is None:       # get
1554
1534
            self.disable()
1555
1535
    
1556
1536
    # LastCheckedOK - property
1557
 
    @dbus_service_property(_interface,
1558
 
                           signature="s",
 
1537
    @dbus_service_property(_interface, signature="s",
1559
1538
                           access="readwrite")
1560
1539
    def LastCheckedOK_dbus_property(self, value=None):
1561
1540
        if value is not None:
1564
1543
        return datetime_to_dbus(self.last_checked_ok)
1565
1544
    
1566
1545
    # LastCheckerStatus - property
1567
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1546
    @dbus_service_property(_interface, signature="n",
 
1547
                           access="read")
1568
1548
    def LastCheckerStatus_dbus_property(self):
1569
1549
        return dbus.Int16(self.last_checker_status)
1570
1550
    
1579
1559
        return datetime_to_dbus(self.last_approval_request)
1580
1560
    
1581
1561
    # Timeout - property
1582
 
    @dbus_service_property(_interface,
1583
 
                           signature="t",
 
1562
    @dbus_service_property(_interface, signature="t",
1584
1563
                           access="readwrite")
1585
1564
    def Timeout_dbus_property(self, value=None):
1586
1565
        if value is None:       # get
1599
1578
                    is None):
1600
1579
                    return
1601
1580
                gobject.source_remove(self.disable_initiator_tag)
1602
 
                self.disable_initiator_tag = gobject.timeout_add(
1603
 
                    int((self.expires - now).total_seconds() * 1000),
1604
 
                    self.disable)
 
1581
                self.disable_initiator_tag = (
 
1582
                    gobject.timeout_add(
 
1583
                        int((self.expires - now).total_seconds()
 
1584
                            * 1000), self.disable))
1605
1585
    
1606
1586
    # ExtendedTimeout - property
1607
 
    @dbus_service_property(_interface,
1608
 
                           signature="t",
 
1587
    @dbus_service_property(_interface, signature="t",
1609
1588
                           access="readwrite")
1610
1589
    def ExtendedTimeout_dbus_property(self, value=None):
1611
1590
        if value is None:       # get
1614
1593
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1615
1594
    
1616
1595
    # Interval - property
1617
 
    @dbus_service_property(_interface,
1618
 
                           signature="t",
 
1596
    @dbus_service_property(_interface, signature="t",
1619
1597
                           access="readwrite")
1620
1598
    def Interval_dbus_property(self, value=None):
1621
1599
        if value is None:       # get
1626
1604
        if self.enabled:
1627
1605
            # Reschedule checker run
1628
1606
            gobject.source_remove(self.checker_initiator_tag)
1629
 
            self.checker_initiator_tag = gobject.timeout_add(
1630
 
                value, self.start_checker)
1631
 
            self.start_checker() # Start one now, too
 
1607
            self.checker_initiator_tag = (gobject.timeout_add
 
1608
                                          (value, self.start_checker))
 
1609
            self.start_checker()    # Start one now, too
1632
1610
    
1633
1611
    # Checker - property
1634
 
    @dbus_service_property(_interface,
1635
 
                           signature="s",
 
1612
    @dbus_service_property(_interface, signature="s",
1636
1613
                           access="readwrite")
1637
1614
    def Checker_dbus_property(self, value=None):
1638
1615
        if value is None:       # get
1640
1617
        self.checker_command = str(value)
1641
1618
    
1642
1619
    # CheckerRunning - property
1643
 
    @dbus_service_property(_interface,
1644
 
                           signature="b",
 
1620
    @dbus_service_property(_interface, signature="b",
1645
1621
                           access="readwrite")
1646
1622
    def CheckerRunning_dbus_property(self, value=None):
1647
1623
        if value is None:       # get
1657
1633
        return self.dbus_object_path # is already a dbus.ObjectPath
1658
1634
    
1659
1635
    # Secret = property
1660
 
    @dbus_service_property(_interface,
1661
 
                           signature="ay",
1662
 
                           access="write",
1663
 
                           byte_arrays=True)
 
1636
    @dbus_service_property(_interface, signature="ay",
 
1637
                           access="write", byte_arrays=True)
1664
1638
    def Secret_dbus_property(self, value):
1665
1639
        self.secret = bytes(value)
1666
1640
    
1672
1646
        self._pipe = child_pipe
1673
1647
        self._pipe.send(('init', fpr, address))
1674
1648
        if not self._pipe.recv():
1675
 
            raise KeyError(fpr)
 
1649
            raise KeyError()
1676
1650
    
1677
1651
    def __getattribute__(self, name):
1678
1652
        if name == '_pipe':
1682
1656
        if data[0] == 'data':
1683
1657
            return data[1]
1684
1658
        if data[0] == 'function':
1685
 
            
1686
1659
            def func(*args, **kwargs):
1687
1660
                self._pipe.send(('funcall', name, args, kwargs))
1688
1661
                return self._pipe.recv()[1]
1689
 
            
1690
1662
            return func
1691
1663
    
1692
1664
    def __setattr__(self, name, value):
1708
1680
            logger.debug("Pipe FD: %d",
1709
1681
                         self.server.child_pipe.fileno())
1710
1682
            
1711
 
            session = gnutls.connection.ClientSession(
1712
 
                self.request, gnutls.connection .X509Credentials())
 
1683
            session = (gnutls.connection
 
1684
                       .ClientSession(self.request,
 
1685
                                      gnutls.connection
 
1686
                                      .X509Credentials()))
1713
1687
            
1714
1688
            # Note: gnutls.connection.X509Credentials is really a
1715
1689
            # generic GnuTLS certificate credentials object so long as
1724
1698
            priority = self.server.gnutls_priority
1725
1699
            if priority is None:
1726
1700
                priority = "NORMAL"
1727
 
            gnutls.library.functions.gnutls_priority_set_direct(
1728
 
                session._c_object, priority, None)
 
1701
            (gnutls.library.functions
 
1702
             .gnutls_priority_set_direct(session._c_object,
 
1703
                                         priority, None))
1729
1704
            
1730
1705
            # Start communication using the Mandos protocol
1731
1706
            # Get protocol number
1751
1726
            approval_required = False
1752
1727
            try:
1753
1728
                try:
1754
 
                    fpr = self.fingerprint(
1755
 
                        self.peer_certificate(session))
 
1729
                    fpr = self.fingerprint(self.peer_certificate
 
1730
                                           (session))
1756
1731
                except (TypeError,
1757
1732
                        gnutls.errors.GNUTLSError) as error:
1758
1733
                    logger.warning("Bad certificate: %s", error)
1773
1748
                while True:
1774
1749
                    if not client.enabled:
1775
1750
                        logger.info("Client %s is disabled",
1776
 
                                    client.name)
 
1751
                                       client.name)
1777
1752
                        if self.server.use_dbus:
1778
1753
                            # Emit D-Bus signal
1779
1754
                            client.Rejected("Disabled")
1826
1801
                        logger.warning("gnutls send failed",
1827
1802
                                       exc_info=error)
1828
1803
                        return
1829
 
                    logger.debug("Sent: %d, remaining: %d", sent,
1830
 
                                 len(client.secret) - (sent_size
1831
 
                                                       + sent))
 
1804
                    logger.debug("Sent: %d, remaining: %d",
 
1805
                                 sent, len(client.secret)
 
1806
                                 - (sent_size + sent))
1832
1807
                    sent_size += sent
1833
1808
                
1834
1809
                logger.info("Sending secret to %s", client.name)
1851
1826
    def peer_certificate(session):
1852
1827
        "Return the peer's OpenPGP certificate as a bytestring"
1853
1828
        # If not an OpenPGP certificate...
1854
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1855
 
                session._c_object)
 
1829
        if (gnutls.library.functions
 
1830
            .gnutls_certificate_type_get(session._c_object)
1856
1831
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1857
1832
            # ...do the normal thing
1858
1833
            return session.peer_certificate
1872
1847
    def fingerprint(openpgp):
1873
1848
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1874
1849
        # New GnuTLS "datum" with the OpenPGP public key
1875
 
        datum = gnutls.library.types.gnutls_datum_t(
1876
 
            ctypes.cast(ctypes.c_char_p(openpgp),
1877
 
                        ctypes.POINTER(ctypes.c_ubyte)),
1878
 
            ctypes.c_uint(len(openpgp)))
 
1850
        datum = (gnutls.library.types
 
1851
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1852
                                             ctypes.POINTER
 
1853
                                             (ctypes.c_ubyte)),
 
1854
                                 ctypes.c_uint(len(openpgp))))
1879
1855
        # New empty GnuTLS certificate
1880
1856
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1881
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1882
 
            ctypes.byref(crt))
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1883
1859
        # Import the OpenPGP public key into the certificate
1884
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1885
 
            crt, ctypes.byref(datum),
1886
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1860
        (gnutls.library.functions
 
1861
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1862
                                    gnutls.library.constants
 
1863
                                    .GNUTLS_OPENPGP_FMT_RAW))
1887
1864
        # Verify the self signature in the key
1888
1865
        crtverify = ctypes.c_uint()
1889
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
 
            crt, 0, ctypes.byref(crtverify))
 
1866
        (gnutls.library.functions
 
1867
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1868
                                         ctypes.byref(crtverify)))
1891
1869
        if crtverify.value != 0:
1892
1870
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1893
 
            raise gnutls.errors.CertificateSecurityError(
1894
 
                "Verify failed")
 
1871
            raise (gnutls.errors.CertificateSecurityError
 
1872
                   ("Verify failed"))
1895
1873
        # New buffer for the fingerprint
1896
1874
        buf = ctypes.create_string_buffer(20)
1897
1875
        buf_len = ctypes.c_size_t()
1898
1876
        # Get the fingerprint from the certificate into the buffer
1899
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1877
        (gnutls.library.functions
 
1878
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1879
                                             ctypes.byref(buf_len)))
1901
1880
        # Deinit the certificate
1902
1881
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1903
1882
        # Convert the buffer to a Python bytestring
1909
1888
 
1910
1889
class MultiprocessingMixIn(object):
1911
1890
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1912
 
    
1913
1891
    def sub_process_main(self, request, address):
1914
1892
        try:
1915
1893
            self.finish_request(request, address)
1927
1905
 
1928
1906
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1929
1907
    """ adds a pipe to the MixIn """
1930
 
    
1931
1908
    def process_request(self, request, client_address):
1932
1909
        """Overrides and wraps the original process_request().
1933
1910
        
1954
1931
        interface:      None or a network interface name (string)
1955
1932
        use_ipv6:       Boolean; to use IPv6 or not
1956
1933
    """
1957
 
    
1958
1934
    def __init__(self, server_address, RequestHandlerClass,
1959
 
                 interface=None,
1960
 
                 use_ipv6=True,
1961
 
                 socketfd=None):
 
1935
                 interface=None, use_ipv6=True, socketfd=None):
1962
1936
        """If socketfd is set, use that file descriptor instead of
1963
1937
        creating a new one with socket.socket().
1964
1938
        """
2005
1979
                             self.interface)
2006
1980
            else:
2007
1981
                try:
2008
 
                    self.socket.setsockopt(
2009
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2010
 
                        (self.interface + "\0").encode("utf-8"))
 
1982
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1983
                                           SO_BINDTODEVICE,
 
1984
                                           (self.interface + "\0")
 
1985
                                           .encode("utf-8"))
2011
1986
                except socket.error as error:
2012
1987
                    if error.errno == errno.EPERM:
2013
1988
                        logger.error("No permission to bind to"
2031
2006
                self.server_address = (any_address,
2032
2007
                                       self.server_address[1])
2033
2008
            elif not self.server_address[1]:
2034
 
                self.server_address = (self.server_address[0], 0)
 
2009
                self.server_address = (self.server_address[0],
 
2010
                                       0)
2035
2011
#                 if self.interface:
2036
2012
#                     self.server_address = (self.server_address[0],
2037
2013
#                                            0, # port
2051
2027
    
2052
2028
    Assumes a gobject.MainLoop event loop.
2053
2029
    """
2054
 
    
2055
2030
    def __init__(self, server_address, RequestHandlerClass,
2056
 
                 interface=None,
2057
 
                 use_ipv6=True,
2058
 
                 clients=None,
2059
 
                 gnutls_priority=None,
2060
 
                 use_dbus=True,
2061
 
                 socketfd=None):
 
2031
                 interface=None, use_ipv6=True, clients=None,
 
2032
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2062
2033
        self.enabled = False
2063
2034
        self.clients = clients
2064
2035
        if self.clients is None:
2070
2041
                                interface = interface,
2071
2042
                                use_ipv6 = use_ipv6,
2072
2043
                                socketfd = socketfd)
2073
 
    
2074
2044
    def server_activate(self):
2075
2045
        if self.enabled:
2076
2046
            return socketserver.TCPServer.server_activate(self)
2080
2050
    
2081
2051
    def add_pipe(self, parent_pipe, proc):
2082
2052
        # Call "handle_ipc" for both data and EOF events
2083
 
        gobject.io_add_watch(
2084
 
            parent_pipe.fileno(),
2085
 
            gobject.IO_IN | gobject.IO_HUP,
2086
 
            functools.partial(self.handle_ipc,
2087
 
                              parent_pipe = parent_pipe,
2088
 
                              proc = proc))
 
2053
        gobject.io_add_watch(parent_pipe.fileno(),
 
2054
                             gobject.IO_IN | gobject.IO_HUP,
 
2055
                             functools.partial(self.handle_ipc,
 
2056
                                               parent_pipe =
 
2057
                                               parent_pipe,
 
2058
                                               proc = proc))
2089
2059
    
2090
 
    def handle_ipc(self, source, condition,
2091
 
                   parent_pipe=None,
2092
 
                   proc = None,
2093
 
                   client_object=None):
 
2060
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2061
                   proc = None, client_object=None):
2094
2062
        # error, or the other end of multiprocessing.Pipe has closed
2095
2063
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2096
2064
            # Wait for other process to exit
2119
2087
                parent_pipe.send(False)
2120
2088
                return False
2121
2089
            
2122
 
            gobject.io_add_watch(
2123
 
                parent_pipe.fileno(),
2124
 
                gobject.IO_IN | gobject.IO_HUP,
2125
 
                functools.partial(self.handle_ipc,
2126
 
                                  parent_pipe = parent_pipe,
2127
 
                                  proc = proc,
2128
 
                                  client_object = client))
 
2090
            gobject.io_add_watch(parent_pipe.fileno(),
 
2091
                                 gobject.IO_IN | gobject.IO_HUP,
 
2092
                                 functools.partial(self.handle_ipc,
 
2093
                                                   parent_pipe =
 
2094
                                                   parent_pipe,
 
2095
                                                   proc = proc,
 
2096
                                                   client_object =
 
2097
                                                   client))
2129
2098
            parent_pipe.send(True)
2130
2099
            # remove the old hook in favor of the new above hook on
2131
2100
            # same fileno
2137
2106
            
2138
2107
            parent_pipe.send(('data', getattr(client_object,
2139
2108
                                              funcname)(*args,
2140
 
                                                        **kwargs)))
 
2109
                                                         **kwargs)))
2141
2110
        
2142
2111
        if command == 'getattr':
2143
2112
            attrname = request[1]
2144
 
            if isinstance(client_object.__getattribute__(attrname),
2145
 
                          collections.Callable):
2146
 
                parent_pipe.send(('function', ))
 
2113
            if callable(client_object.__getattribute__(attrname)):
 
2114
                parent_pipe.send(('function',))
2147
2115
            else:
2148
 
                parent_pipe.send((
2149
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2150
2118
        
2151
2119
        if command == 'setattr':
2152
2120
            attrname = request[1]
2183
2151
    # avoid excessive use of external libraries.
2184
2152
    
2185
2153
    # New type for defining tokens, syntax, and semantics all-in-one
2186
 
    Token = collections.namedtuple("Token", (
2187
 
        "regexp",  # To match token; if "value" is not None, must have
2188
 
                   # a "group" containing digits
2189
 
        "value",   # datetime.timedelta or None
2190
 
        "followers"))           # Tokens valid after this token
 
2154
    Token = collections.namedtuple("Token",
 
2155
                                   ("regexp", # To match token; if
 
2156
                                              # "value" is not None,
 
2157
                                              # must have a "group"
 
2158
                                              # containing digits
 
2159
                                    "value",  # datetime.timedelta or
 
2160
                                              # None
 
2161
                                    "followers")) # Tokens valid after
 
2162
                                                  # this token
2191
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2192
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2193
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2194
2166
    token_second = Token(re.compile(r"(\d+)S"),
2195
2167
                         datetime.timedelta(seconds=1),
2196
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2197
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2198
2170
                         datetime.timedelta(minutes=1),
2199
2171
                         frozenset((token_second, token_end)))
2215
2187
                       frozenset((token_month, token_end)))
2216
2188
    token_week = Token(re.compile(r"(\d+)W"),
2217
2189
                       datetime.timedelta(weeks=1),
2218
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2219
2191
    token_duration = Token(re.compile(r"P"), None,
2220
2192
                           frozenset((token_year, token_month,
2221
2193
                                      token_day, token_time,
2223
2195
    # Define starting values
2224
2196
    value = datetime.timedelta() # Value so far
2225
2197
    found_token = None
2226
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2198
    followers = frozenset((token_duration,)) # Following valid tokens
2227
2199
    s = duration                # String left to parse
2228
2200
    # Loop until end token is found
2229
2201
    while found_token is not token_end:
2246
2218
                break
2247
2219
        else:
2248
2220
            # No currently valid tokens were found
2249
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2250
 
                             .format(duration))
 
2221
            raise ValueError("Invalid RFC 3339 duration")
2251
2222
    # End token found
2252
2223
    return value
2253
2224
 
2290
2261
            elif suffix == "w":
2291
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2292
2263
            else:
2293
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2294
2266
        except IndexError as e:
2295
2267
            raise ValueError(*(e.args))
2296
2268
        timevalue += delta
2312
2284
        # Close all standard open file descriptors
2313
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2314
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2315
 
            raise OSError(errno.ENODEV,
2316
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2317
2288
                          .format(os.devnull))
2318
2289
        os.dup2(null, sys.stdin.fileno())
2319
2290
        os.dup2(null, sys.stdout.fileno())
2385
2356
                        "port": "",
2386
2357
                        "debug": "False",
2387
2358
                        "priority":
2388
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2389
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2359
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2390
2360
                        "servicename": "Mandos",
2391
2361
                        "use_dbus": "True",
2392
2362
                        "use_ipv6": "True",
2396
2366
                        "statedir": "/var/lib/mandos",
2397
2367
                        "foreground": "False",
2398
2368
                        "zeroconf": "True",
2399
 
                    }
 
2369
                        }
2400
2370
    
2401
2371
    # Parse config file for server-global settings
2402
2372
    server_config = configparser.SafeConfigParser(server_defaults)
2403
2373
    del server_defaults
2404
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2374
    server_config.read(os.path.join(options.configdir,
 
2375
                                    "mandos.conf"))
2405
2376
    # Convert the SafeConfigParser object to a dict
2406
2377
    server_settings = server_config.defaults()
2407
2378
    # Use the appropriate methods on the non-string config options
2425
2396
    # Override the settings from the config file with command line
2426
2397
    # options, if set.
2427
2398
    for option in ("interface", "address", "port", "debug",
2428
 
                   "priority", "servicename", "configdir", "use_dbus",
2429
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2430
 
                   "socket", "foreground", "zeroconf"):
 
2399
                   "priority", "servicename", "configdir",
 
2400
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2401
                   "statedir", "socket", "foreground", "zeroconf"):
2431
2402
        value = getattr(options, option)
2432
2403
        if value is not None:
2433
2404
            server_settings[option] = value
2448
2419
    
2449
2420
    ##################################################################
2450
2421
    
2451
 
    if (not server_settings["zeroconf"]
2452
 
        and not (server_settings["port"]
2453
 
                 or server_settings["socket"] != "")):
2454
 
        parser.error("Needs port or socket to work without Zeroconf")
 
2422
    if (not server_settings["zeroconf"] and
 
2423
        not (server_settings["port"]
 
2424
             or server_settings["socket"] != "")):
 
2425
            parser.error("Needs port or socket to work without"
 
2426
                         " Zeroconf")
2455
2427
    
2456
2428
    # For convenience
2457
2429
    debug = server_settings["debug"]
2473
2445
            initlogger(debug, level)
2474
2446
    
2475
2447
    if server_settings["servicename"] != "Mandos":
2476
 
        syslogger.setFormatter(
2477
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2478
 
                              ' %(levelname)s: %(message)s'.format(
2479
 
                                  server_settings["servicename"])))
 
2448
        syslogger.setFormatter(logging.Formatter
 
2449
                               ('Mandos ({}) [%(process)d]:'
 
2450
                                ' %(levelname)s: %(message)s'
 
2451
                                .format(server_settings
 
2452
                                        ["servicename"])))
2480
2453
    
2481
2454
    # Parse config file with clients
2482
2455
    client_config = configparser.SafeConfigParser(Client
2490
2463
    socketfd = None
2491
2464
    if server_settings["socket"] != "":
2492
2465
        socketfd = server_settings["socket"]
2493
 
    tcp_server = MandosServer(
2494
 
        (server_settings["address"], server_settings["port"]),
2495
 
        ClientHandler,
2496
 
        interface=(server_settings["interface"] or None),
2497
 
        use_ipv6=use_ipv6,
2498
 
        gnutls_priority=server_settings["priority"],
2499
 
        use_dbus=use_dbus,
2500
 
        socketfd=socketfd)
 
2466
    tcp_server = MandosServer((server_settings["address"],
 
2467
                               server_settings["port"]),
 
2468
                              ClientHandler,
 
2469
                              interface=(server_settings["interface"]
 
2470
                                         or None),
 
2471
                              use_ipv6=use_ipv6,
 
2472
                              gnutls_priority=
 
2473
                              server_settings["priority"],
 
2474
                              use_dbus=use_dbus,
 
2475
                              socketfd=socketfd)
2501
2476
    if not foreground:
2502
2477
        pidfilename = "/run/mandos.pid"
2503
2478
        if not os.path.isdir("/run/."):
2504
2479
            pidfilename = "/var/run/mandos.pid"
2505
2480
        pidfile = None
2506
2481
        try:
2507
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2482
            pidfile = open(pidfilename, "w")
2508
2483
        except IOError as e:
2509
2484
            logger.error("Could not open file %r", pidfilename,
2510
2485
                         exc_info=e)
2537
2512
        def debug_gnutls(level, string):
2538
2513
            logger.debug("GnuTLS: %s", string[:-1])
2539
2514
        
2540
 
        gnutls.library.functions.gnutls_global_set_log_function(
2541
 
            debug_gnutls)
 
2515
        (gnutls.library.functions
 
2516
         .gnutls_global_set_log_function(debug_gnutls))
2542
2517
        
2543
2518
        # Redirect stdin so all checkers get /dev/null
2544
2519
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2564
2539
    if use_dbus:
2565
2540
        try:
2566
2541
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2567
 
                                            bus,
2568
 
                                            do_not_queue=True)
2569
 
            old_bus_name = dbus.service.BusName(
2570
 
                "se.bsnet.fukt.Mandos", bus,
2571
 
                do_not_queue=True)
2572
 
        except dbus.exceptions.DBusException as e:
 
2542
                                            bus, do_not_queue=True)
 
2543
            old_bus_name = (dbus.service.BusName
 
2544
                            ("se.bsnet.fukt.Mandos", bus,
 
2545
                             do_not_queue=True))
 
2546
        except dbus.exceptions.NameExistsException as e:
2573
2547
            logger.error("Disabling D-Bus:", exc_info=e)
2574
2548
            use_dbus = False
2575
2549
            server_settings["use_dbus"] = False
2576
2550
            tcp_server.use_dbus = False
2577
2551
    if zeroconf:
2578
2552
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2579
 
        service = AvahiServiceToSyslog(
2580
 
            name = server_settings["servicename"],
2581
 
            servicetype = "_mandos._tcp",
2582
 
            protocol = protocol,
2583
 
            bus = bus)
 
2553
        service = AvahiServiceToSyslog(name =
 
2554
                                       server_settings["servicename"],
 
2555
                                       servicetype = "_mandos._tcp",
 
2556
                                       protocol = protocol, bus = bus)
2584
2557
        if server_settings["interface"]:
2585
 
            service.interface = if_nametoindex(
2586
 
                server_settings["interface"].encode("utf-8"))
 
2558
            service.interface = (if_nametoindex
 
2559
                                 (server_settings["interface"]
 
2560
                                  .encode("utf-8")))
2587
2561
    
2588
2562
    global multiprocessing_manager
2589
2563
    multiprocessing_manager = multiprocessing.Manager()
2608
2582
    if server_settings["restore"]:
2609
2583
        try:
2610
2584
            with open(stored_state_path, "rb") as stored_state:
2611
 
                clients_data, old_client_settings = pickle.load(
2612
 
                    stored_state)
 
2585
                clients_data, old_client_settings = (pickle.load
 
2586
                                                     (stored_state))
2613
2587
            os.remove(stored_state_path)
2614
2588
        except IOError as e:
2615
2589
            if e.errno == errno.ENOENT:
2616
 
                logger.warning("Could not load persistent state:"
2617
 
                               " {}".format(os.strerror(e.errno)))
 
2590
                logger.warning("Could not load persistent state: {}"
 
2591
                                .format(os.strerror(e.errno)))
2618
2592
            else:
2619
2593
                logger.critical("Could not load persistent state:",
2620
2594
                                exc_info=e)
2621
2595
                raise
2622
2596
        except EOFError as e:
2623
2597
            logger.warning("Could not load persistent state: "
2624
 
                           "EOFError:",
2625
 
                           exc_info=e)
 
2598
                           "EOFError:", exc_info=e)
2626
2599
    
2627
2600
    with PGPEngine() as pgp:
2628
2601
        for client_name, client in clients_data.items():
2640
2613
                    # For each value in new config, check if it
2641
2614
                    # differs from the old config value (Except for
2642
2615
                    # the "secret" attribute)
2643
 
                    if (name != "secret"
2644
 
                        and (value !=
2645
 
                             old_client_settings[client_name][name])):
 
2616
                    if (name != "secret" and
 
2617
                        value != old_client_settings[client_name]
 
2618
                        [name]):
2646
2619
                        client[name] = value
2647
2620
                except KeyError:
2648
2621
                    pass
2649
2622
            
2650
2623
            # Clients who has passed its expire date can still be
2651
 
            # enabled if its last checker was successful.  A Client
 
2624
            # enabled if its last checker was successful.  Clients
2652
2625
            # whose checker succeeded before we stored its state is
2653
2626
            # assumed to have successfully run all checkers during
2654
2627
            # downtime.
2657
2630
                    if not client["last_checked_ok"]:
2658
2631
                        logger.warning(
2659
2632
                            "disabling client {} - Client never "
2660
 
                            "performed a successful checker".format(
2661
 
                                client_name))
 
2633
                            "performed a successful checker"
 
2634
                            .format(client_name))
2662
2635
                        client["enabled"] = False
2663
2636
                    elif client["last_checker_status"] != 0:
2664
2637
                        logger.warning(
2665
2638
                            "disabling client {} - Client last"
2666
 
                            " checker failed with error code"
2667
 
                            " {}".format(
2668
 
                                client_name,
2669
 
                                client["last_checker_status"]))
 
2639
                            " checker failed with error code {}"
 
2640
                            .format(client_name,
 
2641
                                    client["last_checker_status"]))
2670
2642
                        client["enabled"] = False
2671
2643
                    else:
2672
 
                        client["expires"] = (
2673
 
                            datetime.datetime.utcnow()
2674
 
                            + client["timeout"])
 
2644
                        client["expires"] = (datetime.datetime
 
2645
                                             .utcnow()
 
2646
                                             + client["timeout"])
2675
2647
                        logger.debug("Last checker succeeded,"
2676
 
                                     " keeping {} enabled".format(
2677
 
                                         client_name))
 
2648
                                     " keeping {} enabled"
 
2649
                                     .format(client_name))
2678
2650
            try:
2679
 
                client["secret"] = pgp.decrypt(
2680
 
                    client["encrypted_secret"],
2681
 
                    client_settings[client_name]["secret"])
 
2651
                client["secret"] = (
 
2652
                    pgp.decrypt(client["encrypted_secret"],
 
2653
                                client_settings[client_name]
 
2654
                                ["secret"]))
2682
2655
            except PGPError:
2683
2656
                # If decryption fails, we use secret from new settings
2684
 
                logger.debug("Failed to decrypt {} old secret".format(
2685
 
                    client_name))
2686
 
                client["secret"] = (client_settings[client_name]
2687
 
                                    ["secret"])
 
2657
                logger.debug("Failed to decrypt {} old secret"
 
2658
                             .format(client_name))
 
2659
                client["secret"] = (
 
2660
                    client_settings[client_name]["secret"])
2688
2661
    
2689
2662
    # Add/remove clients based on new changes made to config
2690
2663
    for client_name in (set(old_client_settings)
2697
2670
    # Create all client objects
2698
2671
    for client_name, client in clients_data.items():
2699
2672
        tcp_server.clients[client_name] = client_class(
2700
 
            name = client_name,
2701
 
            settings = client,
 
2673
            name = client_name, settings = client,
2702
2674
            server_settings = server_settings)
2703
2675
    
2704
2676
    if not tcp_server.clients:
2706
2678
    
2707
2679
    if not foreground:
2708
2680
        if pidfile is not None:
2709
 
            pid = os.getpid()
2710
2681
            try:
2711
2682
                with pidfile:
2712
 
                    print(pid, file=pidfile)
 
2683
                    pid = os.getpid()
 
2684
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2713
2685
            except IOError:
2714
2686
                logger.error("Could not write to file %r with PID %d",
2715
2687
                             pidfilename, pid)
2720
2692
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2721
2693
    
2722
2694
    if use_dbus:
2723
 
        
2724
 
        @alternate_dbus_interfaces(
2725
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2695
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2696
                                        "se.bsnet.fukt.Mandos"})
2726
2697
        class MandosDBusService(DBusObjectWithProperties):
2727
2698
            """A D-Bus proxy object"""
2728
 
            
2729
2699
            def __init__(self):
2730
2700
                dbus.service.Object.__init__(self, bus, "/")
2731
 
            
2732
2701
            _interface = "se.recompile.Mandos"
2733
2702
            
2734
2703
            @dbus_interface_annotations(_interface)
2735
2704
            def _foo(self):
2736
 
                return {
2737
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2738
 
                    "false" }
 
2705
                return { "org.freedesktop.DBus.Property"
 
2706
                         ".EmitsChangedSignal":
 
2707
                             "false"}
2739
2708
            
2740
2709
            @dbus.service.signal(_interface, signature="o")
2741
2710
            def ClientAdded(self, objpath):
2755
2724
            @dbus.service.method(_interface, out_signature="ao")
2756
2725
            def GetAllClients(self):
2757
2726
                "D-Bus method"
2758
 
                return dbus.Array(c.dbus_object_path for c in
 
2727
                return dbus.Array(c.dbus_object_path
 
2728
                                  for c in
2759
2729
                                  tcp_server.clients.itervalues())
2760
2730
            
2761
2731
            @dbus.service.method(_interface,
2810
2780
                # + secret.
2811
2781
                exclude = { "bus", "changedstate", "secret",
2812
2782
                            "checker", "server_settings" }
2813
 
                for name, typ in inspect.getmembers(dbus.service
2814
 
                                                    .Object):
 
2783
                for name, typ in (inspect.getmembers
 
2784
                                  (dbus.service.Object)):
2815
2785
                    exclude.add(name)
2816
2786
                
2817
2787
                client_dict["encrypted_secret"] = (client
2824
2794
                del client_settings[client.name]["secret"]
2825
2795
        
2826
2796
        try:
2827
 
            with tempfile.NamedTemporaryFile(
2828
 
                    mode='wb',
2829
 
                    suffix=".pickle",
2830
 
                    prefix='clients-',
2831
 
                    dir=os.path.dirname(stored_state_path),
2832
 
                    delete=False) as stored_state:
 
2797
            with (tempfile.NamedTemporaryFile
 
2798
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2799
                   dir=os.path.dirname(stored_state_path),
 
2800
                   delete=False)) as stored_state:
2833
2801
                pickle.dump((clients, client_settings), stored_state)
2834
 
                tempname = stored_state.name
 
2802
                tempname=stored_state.name
2835
2803
            os.rename(tempname, stored_state_path)
2836
2804
        except (IOError, OSError) as e:
2837
2805
            if not debug:
2856
2824
            client.disable(quiet=True)
2857
2825
            if use_dbus:
2858
2826
                # Emit D-Bus signal
2859
 
                mandos_dbus_service.ClientRemoved(
2860
 
                    client.dbus_object_path, client.name)
 
2827
                mandos_dbus_service.ClientRemoved(client
 
2828
                                                  .dbus_object_path,
 
2829
                                                  client.name)
2861
2830
        client_settings.clear()
2862
2831
    
2863
2832
    atexit.register(cleanup)
2916
2885
    # Must run before the D-Bus bus name gets deregistered
2917
2886
    cleanup()
2918
2887
 
2919
 
 
2920
2888
if __name__ == '__main__':
2921
2889
    main()