/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-04-02 18:59:29 UTC
  • Revision ID: teddy@recompile.se-20150402185929-1q1rf1zelbpzzn74
Add "!RSA" also to examples/documentation.

* mandos.conf (priority): Add "!RSA" to default commented-out value.
* mandos.conf.xml (EXAMPLE): Add "!RSA" to example priority setting.

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
409
 
474
456
                          "fingerprint", "host", "interval",
475
457
                          "last_approval_request", "last_checked_ok",
476
458
                          "last_enabled", "name", "timeout")
477
 
    client_defaults = {
478
 
        "timeout": "PT5M",
479
 
        "extended_timeout": "PT15M",
480
 
        "interval": "PT2M",
481
 
        "checker": "fping -q -- %%(host)s",
482
 
        "host": "",
483
 
        "approval_delay": "PT0S",
484
 
        "approval_duration": "PT1S",
485
 
        "approved_by_default": "True",
486
 
        "enabled": "True",
487
 
    }
 
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
                        }
488
469
    
489
470
    @staticmethod
490
471
    def config_parser(config):
568
549
        self.current_checker_command = None
569
550
        self.approved = None
570
551
        self.approvals_pending = 0
571
 
        self.changedstate = multiprocessing_manager.Condition(
572
 
            multiprocessing_manager.Lock())
573
 
        self.client_structure = [attr
574
 
                                 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()
575
557
                                 if not attr.startswith("_")]
576
558
        self.client_structure.append("client_structure")
577
559
        
578
 
        for name, t in inspect.getmembers(
579
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
580
564
            if not name.startswith("_"):
581
565
                self.client_structure.append(name)
582
566
    
624
608
        # and every interval from then on.
625
609
        if self.checker_initiator_tag is not None:
626
610
            gobject.source_remove(self.checker_initiator_tag)
627
 
        self.checker_initiator_tag = gobject.timeout_add(
628
 
            int(self.interval.total_seconds() * 1000),
629
 
            self.start_checker)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
630
615
        # Schedule a disable() when 'timeout' has passed
631
616
        if self.disable_initiator_tag is not None:
632
617
            gobject.source_remove(self.disable_initiator_tag)
633
 
        self.disable_initiator_tag = gobject.timeout_add(
634
 
            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))
635
622
        # Also start a new checker *right now*.
636
623
        self.start_checker()
637
624
    
646
633
                            vars(self))
647
634
                self.checked_ok()
648
635
            else:
649
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
650
638
        else:
651
639
            self.last_checker_status = -1
652
640
            logger.warning("Checker for %(name)s crashed?",
666
654
            gobject.source_remove(self.disable_initiator_tag)
667
655
            self.disable_initiator_tag = None
668
656
        if getattr(self, "enabled", False):
669
 
            self.disable_initiator_tag = gobject.timeout_add(
670
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
671
660
            self.expires = datetime.datetime.utcnow() + timeout
672
661
    
673
662
    def need_approval(self):
704
693
        # Start a new checker if needed
705
694
        if self.checker is None:
706
695
            # Escape attributes for the shell
707
 
            escaped_attrs = {
708
 
                attr: re.escape(str(getattr(self, attr)))
709
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
710
699
            try:
711
700
                command = self.checker_command % escaped_attrs
712
701
            except TypeError as error:
713
702
                logger.error('Could not format string "%s"',
714
 
                             self.checker_command,
715
 
                             exc_info=error)
716
 
                return True     # Try again later
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
717
705
            self.current_checker_command = command
718
706
            try:
719
 
                logger.info("Starting checker %r for %s", command,
720
 
                            self.name)
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
721
709
                # We don't need to redirect stdout and stderr, since
722
710
                # in normal mode, that is already done by daemon(),
723
711
                # and in debug mode we don't want to.  (Stdin is
732
720
                                       "stderr": wnull })
733
721
                self.checker = subprocess.Popen(command,
734
722
                                                close_fds=True,
735
 
                                                shell=True,
736
 
                                                cwd="/",
 
723
                                                shell=True, cwd="/",
737
724
                                                **popen_args)
738
725
            except OSError as error:
739
726
                logger.error("Failed to start subprocess",
740
727
                             exc_info=error)
741
728
                return True
742
 
            self.checker_callback_tag = gobject.child_watch_add(
743
 
                self.checker.pid, self.checker_callback, data=command)
 
729
            self.checker_callback_tag = (gobject.child_watch_add
 
730
                                         (self.checker.pid,
 
731
                                          self.checker_callback,
 
732
                                          data=command))
744
733
            # The checker may have completed before the gobject
745
734
            # watch was added.  Check for this.
746
735
            try:
777
766
        self.checker = None
778
767
 
779
768
 
780
 
def dbus_service_property(dbus_interface,
781
 
                          signature="v",
782
 
                          access="readwrite",
783
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
784
771
    """Decorators for marking methods of a DBusObjectWithProperties to
785
772
    become properties on the D-Bus.
786
773
    
796
783
    if byte_arrays and signature != "ay":
797
784
        raise ValueError("Byte arrays not supported for non-'ay'"
798
785
                         " signature {!r}".format(signature))
799
 
    
800
786
    def decorator(func):
801
787
        func._dbus_is_property = True
802
788
        func._dbus_interface = dbus_interface
807
793
            func._dbus_name = func._dbus_name[:-14]
808
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
809
795
        return func
810
 
    
811
796
    return decorator
812
797
 
813
798
 
822
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
823
808
                    "false"}
824
809
    """
825
 
    
826
810
    def decorator(func):
827
811
        func._dbus_is_interface = True
828
812
        func._dbus_interface = dbus_interface
829
813
        func._dbus_name = dbus_interface
830
814
        return func
831
 
    
832
815
    return decorator
833
816
 
834
817
 
844
827
    def Property_dbus_property(self):
845
828
        return dbus.Boolean(False)
846
829
    """
847
 
    
848
830
    def decorator(func):
849
831
        func._dbus_annotations = annotations
850
832
        return func
851
 
    
852
833
    return decorator
853
834
 
854
835
 
857
838
    """
858
839
    pass
859
840
 
860
 
 
861
841
class DBusPropertyAccessException(DBusPropertyException):
862
842
    """A property's access permissions disallows an operation.
863
843
    """
891
871
    def _get_all_dbus_things(self, thing):
892
872
        """Returns a generator of (name, attribute) pairs
893
873
        """
894
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
895
876
                 athing.__get__(self))
896
877
                for cls in self.__class__.__mro__
897
878
                for name, athing in
898
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
899
881
    
900
882
    def _get_dbus_property(self, interface_name, property_name):
901
883
        """Returns a bound method if one exists which is a D-Bus
902
884
        property with the specified name and interface.
903
885
        """
904
 
        for cls in self.__class__.__mro__:
905
 
            for name, value in inspect.getmembers(
906
 
                    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"))):
907
890
                if (value._dbus_name == property_name
908
891
                    and value._dbus_interface == interface_name):
909
892
                    return value.__get__(self)
910
893
        
911
894
        # No such property
912
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
913
 
            self.dbus_object_path, interface_name, property_name))
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
914
898
    
915
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
916
 
                         in_signature="ss",
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
917
900
                         out_signature="v")
918
901
    def Get(self, interface_name, property_name):
919
902
        """Standard D-Bus property Get() method, see D-Bus standard.
944
927
                                            for byte in value))
945
928
        prop(value)
946
929
    
947
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
948
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
949
931
                         out_signature="a{sv}")
950
932
    def GetAll(self, interface_name):
951
933
        """Standard D-Bus property GetAll() method, see D-Bus
966
948
            if not hasattr(value, "variant_level"):
967
949
                properties[name] = value
968
950
                continue
969
 
            properties[name] = type(value)(
970
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
971
953
        return dbus.Dictionary(properties, signature="sv")
972
954
    
973
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
991
973
                                                   connection)
992
974
        try:
993
975
            document = xml.dom.minidom.parseString(xmlstring)
994
 
            
995
976
            def make_tag(document, name, prop):
996
977
                e = document.createElement("property")
997
978
                e.setAttribute("name", name)
998
979
                e.setAttribute("type", prop._dbus_signature)
999
980
                e.setAttribute("access", prop._dbus_access)
1000
981
                return e
1001
 
            
1002
982
            for if_tag in document.getElementsByTagName("interface"):
1003
983
                # Add property tags
1004
984
                for tag in (make_tag(document, name, prop)
1016
996
                            if (name == tag.getAttribute("name")
1017
997
                                and prop._dbus_interface
1018
998
                                == if_tag.getAttribute("name")):
1019
 
                                annots.update(getattr(
1020
 
                                    prop, "_dbus_annotations", {}))
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
1021
1003
                        for name, value in annots.items():
1022
1004
                            ann_tag = document.createElement(
1023
1005
                                "annotation")
1028
1010
                for annotation, value in dict(
1029
1011
                    itertools.chain.from_iterable(
1030
1012
                        annotations().items()
1031
 
                        for name, annotations
1032
 
                        in self._get_all_dbus_things("interface")
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
1033
1015
                        if name == if_tag.getAttribute("name")
1034
1016
                        )).items():
1035
1017
                    ann_tag = document.createElement("annotation")
1064
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1065
1047
    if dt is None:
1066
1048
        return dbus.String("", variant_level = variant_level)
1067
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1068
1051
 
1069
1052
 
1070
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1090
1073
    (from DBusObjectWithProperties) and interfaces (from the
1091
1074
    dbus_interface_annotations decorator).
1092
1075
    """
1093
 
    
1094
1076
    def wrapper(cls):
1095
1077
        for orig_interface_name, alt_interface_name in (
1096
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1097
1079
            attr = {}
1098
1080
            interface_names = set()
1099
1081
            # Go though all attributes of the class
1101
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1102
1084
                # with the wrong interface name
1103
1085
                if (not hasattr(attribute, "_dbus_interface")
1104
 
                    or not attribute._dbus_interface.startswith(
1105
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1106
1088
                    continue
1107
1089
                # Create an alternate D-Bus interface name based on
1108
1090
                # the current name
1109
 
                alt_interface = attribute._dbus_interface.replace(
1110
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1111
1094
                interface_names.add(alt_interface)
1112
1095
                # Is this a D-Bus signal?
1113
1096
                if getattr(attribute, "_dbus_is_signal", False):
1114
1097
                    # Extract the original non-method undecorated
1115
1098
                    # function by black magic
1116
1099
                    nonmethod_func = (dict(
1117
 
                        zip(attribute.func_code.co_freevars,
1118
 
                            attribute.__closure__))
1119
 
                                      ["func"].cell_contents)
 
1100
                            zip(attribute.func_code.co_freevars,
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1120
1103
                    # Create a new, but exactly alike, function
1121
1104
                    # object, and decorate it to be a new D-Bus signal
1122
1105
                    # with the alternate D-Bus interface name
1123
 
                    new_function = (dbus.service.signal(
1124
 
                        alt_interface, attribute._dbus_signature)
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
1125
1109
                                    (types.FunctionType(
1126
 
                                        nonmethod_func.func_code,
1127
 
                                        nonmethod_func.func_globals,
1128
 
                                        nonmethod_func.func_name,
1129
 
                                        nonmethod_func.func_defaults,
1130
 
                                        nonmethod_func.func_closure)))
 
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)
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
2113
            if callable(client_object.__getattribute__(attrname)):
2145
 
                parent_pipe.send(('function', ))
 
2114
                parent_pipe.send(('function',))
2146
2115
            else:
2147
 
                parent_pipe.send((
2148
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2149
2118
        
2150
2119
        if command == 'setattr':
2151
2120
            attrname = request[1]
2182
2151
    # avoid excessive use of external libraries.
2183
2152
    
2184
2153
    # New type for defining tokens, syntax, and semantics all-in-one
2185
 
    Token = collections.namedtuple("Token", (
2186
 
        "regexp",  # To match token; if "value" is not None, must have
2187
 
                   # a "group" containing digits
2188
 
        "value",   # datetime.timedelta or None
2189
 
        "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
2190
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2191
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2192
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2193
2166
    token_second = Token(re.compile(r"(\d+)S"),
2194
2167
                         datetime.timedelta(seconds=1),
2195
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2196
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2197
2170
                         datetime.timedelta(minutes=1),
2198
2171
                         frozenset((token_second, token_end)))
2214
2187
                       frozenset((token_month, token_end)))
2215
2188
    token_week = Token(re.compile(r"(\d+)W"),
2216
2189
                       datetime.timedelta(weeks=1),
2217
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2218
2191
    token_duration = Token(re.compile(r"P"), None,
2219
2192
                           frozenset((token_year, token_month,
2220
2193
                                      token_day, token_time,
2222
2195
    # Define starting values
2223
2196
    value = datetime.timedelta() # Value so far
2224
2197
    found_token = None
2225
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2198
    followers = frozenset((token_duration,)) # Following valid tokens
2226
2199
    s = duration                # String left to parse
2227
2200
    # Loop until end token is found
2228
2201
    while found_token is not token_end:
2245
2218
                break
2246
2219
        else:
2247
2220
            # No currently valid tokens were found
2248
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2249
 
                             .format(duration))
 
2221
            raise ValueError("Invalid RFC 3339 duration")
2250
2222
    # End token found
2251
2223
    return value
2252
2224
 
2289
2261
            elif suffix == "w":
2290
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2291
2263
            else:
2292
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2293
2266
        except IndexError as e:
2294
2267
            raise ValueError(*(e.args))
2295
2268
        timevalue += delta
2311
2284
        # Close all standard open file descriptors
2312
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2313
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2314
 
            raise OSError(errno.ENODEV,
2315
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2316
2288
                          .format(os.devnull))
2317
2289
        os.dup2(null, sys.stdin.fileno())
2318
2290
        os.dup2(null, sys.stdout.fileno())
2395
2367
                        "statedir": "/var/lib/mandos",
2396
2368
                        "foreground": "False",
2397
2369
                        "zeroconf": "True",
2398
 
                    }
 
2370
                        }
2399
2371
    
2400
2372
    # Parse config file for server-global settings
2401
2373
    server_config = configparser.SafeConfigParser(server_defaults)
2402
2374
    del server_defaults
2403
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2375
    server_config.read(os.path.join(options.configdir,
 
2376
                                    "mandos.conf"))
2404
2377
    # Convert the SafeConfigParser object to a dict
2405
2378
    server_settings = server_config.defaults()
2406
2379
    # Use the appropriate methods on the non-string config options
2424
2397
    # Override the settings from the config file with command line
2425
2398
    # options, if set.
2426
2399
    for option in ("interface", "address", "port", "debug",
2427
 
                   "priority", "servicename", "configdir", "use_dbus",
2428
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2429
 
                   "socket", "foreground", "zeroconf"):
 
2400
                   "priority", "servicename", "configdir",
 
2401
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2402
                   "statedir", "socket", "foreground", "zeroconf"):
2430
2403
        value = getattr(options, option)
2431
2404
        if value is not None:
2432
2405
            server_settings[option] = value
2447
2420
    
2448
2421
    ##################################################################
2449
2422
    
2450
 
    if (not server_settings["zeroconf"]
2451
 
        and not (server_settings["port"]
2452
 
                 or server_settings["socket"] != "")):
2453
 
        parser.error("Needs port or socket to work without Zeroconf")
 
2423
    if (not server_settings["zeroconf"] and
 
2424
        not (server_settings["port"]
 
2425
             or server_settings["socket"] != "")):
 
2426
            parser.error("Needs port or socket to work without"
 
2427
                         " Zeroconf")
2454
2428
    
2455
2429
    # For convenience
2456
2430
    debug = server_settings["debug"]
2472
2446
            initlogger(debug, level)
2473
2447
    
2474
2448
    if server_settings["servicename"] != "Mandos":
2475
 
        syslogger.setFormatter(
2476
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2477
 
                              ' %(levelname)s: %(message)s'.format(
2478
 
                                  server_settings["servicename"])))
 
2449
        syslogger.setFormatter(logging.Formatter
 
2450
                               ('Mandos ({}) [%(process)d]:'
 
2451
                                ' %(levelname)s: %(message)s'
 
2452
                                .format(server_settings
 
2453
                                        ["servicename"])))
2479
2454
    
2480
2455
    # Parse config file with clients
2481
2456
    client_config = configparser.SafeConfigParser(Client
2489
2464
    socketfd = None
2490
2465
    if server_settings["socket"] != "":
2491
2466
        socketfd = server_settings["socket"]
2492
 
    tcp_server = MandosServer(
2493
 
        (server_settings["address"], server_settings["port"]),
2494
 
        ClientHandler,
2495
 
        interface=(server_settings["interface"] or None),
2496
 
        use_ipv6=use_ipv6,
2497
 
        gnutls_priority=server_settings["priority"],
2498
 
        use_dbus=use_dbus,
2499
 
        socketfd=socketfd)
 
2467
    tcp_server = MandosServer((server_settings["address"],
 
2468
                               server_settings["port"]),
 
2469
                              ClientHandler,
 
2470
                              interface=(server_settings["interface"]
 
2471
                                         or None),
 
2472
                              use_ipv6=use_ipv6,
 
2473
                              gnutls_priority=
 
2474
                              server_settings["priority"],
 
2475
                              use_dbus=use_dbus,
 
2476
                              socketfd=socketfd)
2500
2477
    if not foreground:
2501
2478
        pidfilename = "/run/mandos.pid"
2502
2479
        if not os.path.isdir("/run/."):
2503
2480
            pidfilename = "/var/run/mandos.pid"
2504
2481
        pidfile = None
2505
2482
        try:
2506
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2483
            pidfile = open(pidfilename, "w")
2507
2484
        except IOError as e:
2508
2485
            logger.error("Could not open file %r", pidfilename,
2509
2486
                         exc_info=e)
2536
2513
        def debug_gnutls(level, string):
2537
2514
            logger.debug("GnuTLS: %s", string[:-1])
2538
2515
        
2539
 
        gnutls.library.functions.gnutls_global_set_log_function(
2540
 
            debug_gnutls)
 
2516
        (gnutls.library.functions
 
2517
         .gnutls_global_set_log_function(debug_gnutls))
2541
2518
        
2542
2519
        # Redirect stdin so all checkers get /dev/null
2543
2520
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2563
2540
    if use_dbus:
2564
2541
        try:
2565
2542
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2566
 
                                            bus,
2567
 
                                            do_not_queue=True)
2568
 
            old_bus_name = dbus.service.BusName(
2569
 
                "se.bsnet.fukt.Mandos", bus,
2570
 
                do_not_queue=True)
2571
 
        except dbus.exceptions.DBusException as e:
 
2543
                                            bus, do_not_queue=True)
 
2544
            old_bus_name = (dbus.service.BusName
 
2545
                            ("se.bsnet.fukt.Mandos", bus,
 
2546
                             do_not_queue=True))
 
2547
        except dbus.exceptions.NameExistsException as e:
2572
2548
            logger.error("Disabling D-Bus:", exc_info=e)
2573
2549
            use_dbus = False
2574
2550
            server_settings["use_dbus"] = False
2575
2551
            tcp_server.use_dbus = False
2576
2552
    if zeroconf:
2577
2553
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2578
 
        service = AvahiServiceToSyslog(
2579
 
            name = server_settings["servicename"],
2580
 
            servicetype = "_mandos._tcp",
2581
 
            protocol = protocol,
2582
 
            bus = bus)
 
2554
        service = AvahiServiceToSyslog(name =
 
2555
                                       server_settings["servicename"],
 
2556
                                       servicetype = "_mandos._tcp",
 
2557
                                       protocol = protocol, bus = bus)
2583
2558
        if server_settings["interface"]:
2584
 
            service.interface = if_nametoindex(
2585
 
                server_settings["interface"].encode("utf-8"))
 
2559
            service.interface = (if_nametoindex
 
2560
                                 (server_settings["interface"]
 
2561
                                  .encode("utf-8")))
2586
2562
    
2587
2563
    global multiprocessing_manager
2588
2564
    multiprocessing_manager = multiprocessing.Manager()
2607
2583
    if server_settings["restore"]:
2608
2584
        try:
2609
2585
            with open(stored_state_path, "rb") as stored_state:
2610
 
                clients_data, old_client_settings = pickle.load(
2611
 
                    stored_state)
 
2586
                clients_data, old_client_settings = (pickle.load
 
2587
                                                     (stored_state))
2612
2588
            os.remove(stored_state_path)
2613
2589
        except IOError as e:
2614
2590
            if e.errno == errno.ENOENT:
2615
 
                logger.warning("Could not load persistent state:"
2616
 
                               " {}".format(os.strerror(e.errno)))
 
2591
                logger.warning("Could not load persistent state: {}"
 
2592
                                .format(os.strerror(e.errno)))
2617
2593
            else:
2618
2594
                logger.critical("Could not load persistent state:",
2619
2595
                                exc_info=e)
2620
2596
                raise
2621
2597
        except EOFError as e:
2622
2598
            logger.warning("Could not load persistent state: "
2623
 
                           "EOFError:",
2624
 
                           exc_info=e)
 
2599
                           "EOFError:", exc_info=e)
2625
2600
    
2626
2601
    with PGPEngine() as pgp:
2627
2602
        for client_name, client in clients_data.items():
2639
2614
                    # For each value in new config, check if it
2640
2615
                    # differs from the old config value (Except for
2641
2616
                    # the "secret" attribute)
2642
 
                    if (name != "secret"
2643
 
                        and (value !=
2644
 
                             old_client_settings[client_name][name])):
 
2617
                    if (name != "secret" and
 
2618
                        value != old_client_settings[client_name]
 
2619
                        [name]):
2645
2620
                        client[name] = value
2646
2621
                except KeyError:
2647
2622
                    pass
2656
2631
                    if not client["last_checked_ok"]:
2657
2632
                        logger.warning(
2658
2633
                            "disabling client {} - Client never "
2659
 
                            "performed a successful checker".format(
2660
 
                                client_name))
 
2634
                            "performed a successful checker"
 
2635
                            .format(client_name))
2661
2636
                        client["enabled"] = False
2662
2637
                    elif client["last_checker_status"] != 0:
2663
2638
                        logger.warning(
2664
2639
                            "disabling client {} - Client last"
2665
 
                            " checker failed with error code"
2666
 
                            " {}".format(
2667
 
                                client_name,
2668
 
                                client["last_checker_status"]))
 
2640
                            " checker failed with error code {}"
 
2641
                            .format(client_name,
 
2642
                                    client["last_checker_status"]))
2669
2643
                        client["enabled"] = False
2670
2644
                    else:
2671
 
                        client["expires"] = (
2672
 
                            datetime.datetime.utcnow()
2673
 
                            + client["timeout"])
 
2645
                        client["expires"] = (datetime.datetime
 
2646
                                             .utcnow()
 
2647
                                             + client["timeout"])
2674
2648
                        logger.debug("Last checker succeeded,"
2675
 
                                     " keeping {} enabled".format(
2676
 
                                         client_name))
 
2649
                                     " keeping {} enabled"
 
2650
                                     .format(client_name))
2677
2651
            try:
2678
 
                client["secret"] = pgp.decrypt(
2679
 
                    client["encrypted_secret"],
2680
 
                    client_settings[client_name]["secret"])
 
2652
                client["secret"] = (
 
2653
                    pgp.decrypt(client["encrypted_secret"],
 
2654
                                client_settings[client_name]
 
2655
                                ["secret"]))
2681
2656
            except PGPError:
2682
2657
                # If decryption fails, we use secret from new settings
2683
 
                logger.debug("Failed to decrypt {} old secret".format(
2684
 
                    client_name))
2685
 
                client["secret"] = (client_settings[client_name]
2686
 
                                    ["secret"])
 
2658
                logger.debug("Failed to decrypt {} old secret"
 
2659
                             .format(client_name))
 
2660
                client["secret"] = (
 
2661
                    client_settings[client_name]["secret"])
2687
2662
    
2688
2663
    # Add/remove clients based on new changes made to config
2689
2664
    for client_name in (set(old_client_settings)
2696
2671
    # Create all client objects
2697
2672
    for client_name, client in clients_data.items():
2698
2673
        tcp_server.clients[client_name] = client_class(
2699
 
            name = client_name,
2700
 
            settings = client,
 
2674
            name = client_name, settings = client,
2701
2675
            server_settings = server_settings)
2702
2676
    
2703
2677
    if not tcp_server.clients:
2705
2679
    
2706
2680
    if not foreground:
2707
2681
        if pidfile is not None:
2708
 
            pid = os.getpid()
2709
2682
            try:
2710
2683
                with pidfile:
2711
 
                    print(pid, file=pidfile)
 
2684
                    pid = os.getpid()
 
2685
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2712
2686
            except IOError:
2713
2687
                logger.error("Could not write to file %r with PID %d",
2714
2688
                             pidfilename, pid)
2719
2693
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2720
2694
    
2721
2695
    if use_dbus:
2722
 
        
2723
 
        @alternate_dbus_interfaces(
2724
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2696
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2697
                                        "se.bsnet.fukt.Mandos"})
2725
2698
        class MandosDBusService(DBusObjectWithProperties):
2726
2699
            """A D-Bus proxy object"""
2727
 
            
2728
2700
            def __init__(self):
2729
2701
                dbus.service.Object.__init__(self, bus, "/")
2730
 
            
2731
2702
            _interface = "se.recompile.Mandos"
2732
2703
            
2733
2704
            @dbus_interface_annotations(_interface)
2734
2705
            def _foo(self):
2735
 
                return {
2736
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2737
 
                    "false" }
 
2706
                return { "org.freedesktop.DBus.Property"
 
2707
                         ".EmitsChangedSignal":
 
2708
                             "false"}
2738
2709
            
2739
2710
            @dbus.service.signal(_interface, signature="o")
2740
2711
            def ClientAdded(self, objpath):
2754
2725
            @dbus.service.method(_interface, out_signature="ao")
2755
2726
            def GetAllClients(self):
2756
2727
                "D-Bus method"
2757
 
                return dbus.Array(c.dbus_object_path for c in
 
2728
                return dbus.Array(c.dbus_object_path
 
2729
                                  for c in
2758
2730
                                  tcp_server.clients.itervalues())
2759
2731
            
2760
2732
            @dbus.service.method(_interface,
2809
2781
                # + secret.
2810
2782
                exclude = { "bus", "changedstate", "secret",
2811
2783
                            "checker", "server_settings" }
2812
 
                for name, typ in inspect.getmembers(dbus.service
2813
 
                                                    .Object):
 
2784
                for name, typ in (inspect.getmembers
 
2785
                                  (dbus.service.Object)):
2814
2786
                    exclude.add(name)
2815
2787
                
2816
2788
                client_dict["encrypted_secret"] = (client
2823
2795
                del client_settings[client.name]["secret"]
2824
2796
        
2825
2797
        try:
2826
 
            with tempfile.NamedTemporaryFile(
2827
 
                    mode='wb',
2828
 
                    suffix=".pickle",
2829
 
                    prefix='clients-',
2830
 
                    dir=os.path.dirname(stored_state_path),
2831
 
                    delete=False) as stored_state:
 
2798
            with (tempfile.NamedTemporaryFile
 
2799
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2800
                   dir=os.path.dirname(stored_state_path),
 
2801
                   delete=False)) as stored_state:
2832
2802
                pickle.dump((clients, client_settings), stored_state)
2833
 
                tempname = stored_state.name
 
2803
                tempname=stored_state.name
2834
2804
            os.rename(tempname, stored_state_path)
2835
2805
        except (IOError, OSError) as e:
2836
2806
            if not debug:
2855
2825
            client.disable(quiet=True)
2856
2826
            if use_dbus:
2857
2827
                # Emit D-Bus signal
2858
 
                mandos_dbus_service.ClientRemoved(
2859
 
                    client.dbus_object_path, client.name)
 
2828
                mandos_dbus_service.ClientRemoved(client
 
2829
                                                  .dbus_object_path,
 
2830
                                                  client.name)
2860
2831
        client_settings.clear()
2861
2832
    
2862
2833
    atexit.register(cleanup)
2915
2886
    # Must run before the D-Bus bus name gets deregistered
2916
2887
    cleanup()
2917
2888
 
2918
 
 
2919
2889
if __name__ == '__main__':
2920
2890
    main()