/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-03-10 18:03:38 UTC
  • Revision ID: teddy@recompile.se-20150310180338-pcxw6r2qmw9k6br9
Add ":!RSA" to GnuTLS priority string, to disallow non-DHE kx.

If Mandos was somehow made to use a non-ephemeral Diffie-Hellman key
exchange algorithm in the TLS handshake, any saved network traffic
could then be decrypted later if the Mandos client key was obtained.
By default, Mandos uses ephemeral DH key exchanges which does not have
this problem, but a non-ephemeral key exchange algorithm was still
enabled by default.  The simplest solution is to simply turn that off,
which ensures that Mandos will always use ephemeral DH key exchanges.

There is a "PFS" priority string specifier, but we can't use it because:

1. Security-wise, it is a mix between "NORMAL" and "SECURE128" - it
   enables a lot more algorithms than "SECURE256".

2. It is only available since GnuTLS 3.2.4.

Thanks to Andreas Fischer <af@bantuX.org> for reporting this issue.

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
98
98
syslogger = None
99
99
 
100
100
try:
101
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
102
 
        ctypes.util.find_library("c")).if_nametoindex
 
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
102
                      (ctypes.util.find_library("c"))
 
103
                      .if_nametoindex)
103
104
except (OSError, AttributeError):
104
 
    
105
105
    def if_nametoindex(interface):
106
106
        "Get an interface index the hard way, i.e. using fcntl()"
107
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
116
116
    """init logger and add loglevel"""
117
117
    
118
118
    global syslogger
119
 
    syslogger = (logging.handlers.SysLogHandler(
120
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
121
 
        address = "/dev/log"))
 
119
    syslogger = (logging.handlers.SysLogHandler
 
120
                 (facility =
 
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
122
                  address = "/dev/log"))
122
123
    syslogger.setFormatter(logging.Formatter
123
124
                           ('Mandos [%(process)d]: %(levelname)s:'
124
125
                            ' %(message)s'))
141
142
 
142
143
class PGPEngine(object):
143
144
    """A simple class for OpenPGP symmetric encryption & decryption"""
144
 
    
145
145
    def __init__(self):
146
146
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
147
147
        self.gnupgargs = ['--batch',
186
186
    
187
187
    def encrypt(self, data, password):
188
188
        passphrase = self.password_encode(password)
189
 
        with tempfile.NamedTemporaryFile(
190
 
                dir=self.tempdir) as passfile:
 
189
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
190
                                         ) as passfile:
191
191
            passfile.write(passphrase)
192
192
            passfile.flush()
193
193
            proc = subprocess.Popen(['gpg', '--symmetric',
204
204
    
205
205
    def decrypt(self, data, password):
206
206
        passphrase = self.password_encode(password)
207
 
        with tempfile.NamedTemporaryFile(
208
 
                dir = self.tempdir) as passfile:
 
207
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
208
                                         ) as passfile:
209
209
            passfile.write(passphrase)
210
210
            passfile.flush()
211
211
            proc = subprocess.Popen(['gpg', '--decrypt',
215
215
                                    stdin = subprocess.PIPE,
216
216
                                    stdout = subprocess.PIPE,
217
217
                                    stderr = subprocess.PIPE)
218
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
218
            decrypted_plaintext, err = proc.communicate(input
 
219
                                                        = data)
219
220
        if proc.returncode != 0:
220
221
            raise PGPError(err)
221
222
        return decrypted_plaintext
227
228
        return super(AvahiError, self).__init__(value, *args,
228
229
                                                **kwargs)
229
230
 
230
 
 
231
231
class AvahiServiceError(AvahiError):
232
232
    pass
233
233
 
234
 
 
235
234
class AvahiGroupError(AvahiError):
236
235
    pass
237
236
 
257
256
    bus: dbus.SystemBus()
258
257
    """
259
258
    
260
 
    def __init__(self,
261
 
                 interface = avahi.IF_UNSPEC,
262
 
                 name = None,
263
 
                 servicetype = None,
264
 
                 port = None,
265
 
                 TXT = None,
266
 
                 domain = "",
267
 
                 host = "",
268
 
                 max_renames = 32768,
269
 
                 protocol = avahi.PROTO_UNSPEC,
270
 
                 bus = None):
 
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):
271
263
        self.interface = interface
272
264
        self.name = name
273
265
        self.type = servicetype
290
282
                            " after %i retries, exiting.",
291
283
                            self.rename_count)
292
284
            raise AvahiServiceError("Too many renames")
293
 
        self.name = str(
294
 
            self.server.GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
295
287
        self.rename_count += 1
296
288
        logger.info("Changing Zeroconf service name to %r ...",
297
289
                    self.name)
352
344
        elif state == avahi.ENTRY_GROUP_FAILURE:
353
345
            logger.critical("Avahi: Error in group state changed %s",
354
346
                            str(error))
355
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
347
            raise AvahiGroupError("State changed: {!s}"
 
348
                                  .format(error))
356
349
    
357
350
    def cleanup(self):
358
351
        """Derived from the Avahi example code"""
368
361
    def server_state_changed(self, state, error=None):
369
362
        """Derived from the Avahi example code"""
370
363
        logger.debug("Avahi server state change: %i", state)
371
 
        bad_states = {
372
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
373
 
            avahi.SERVER_REGISTERING: None,
374
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
375
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
376
 
        }
 
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" }
377
371
        if state in bad_states:
378
372
            if bad_states[state] is not None:
379
373
                if error is None:
398
392
                                    follow_name_owner_changes=True),
399
393
                avahi.DBUS_INTERFACE_SERVER)
400
394
        self.server.connect_to_signal("StateChanged",
401
 
                                      self.server_state_changed)
 
395
                                 self.server_state_changed)
402
396
        self.server_state_changed(self.server.GetState())
403
397
 
404
398
 
406
400
    def rename(self, *args, **kwargs):
407
401
        """Add the new name to the syslog messages"""
408
402
        ret = AvahiService.rename(self, *args, **kwargs)
409
 
        syslogger.setFormatter(logging.Formatter(
410
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
411
 
            .format(self.name)))
 
403
        syslogger.setFormatter(logging.Formatter
 
404
                               ('Mandos ({}) [%(process)d]:'
 
405
                                ' %(levelname)s: %(message)s'
 
406
                                .format(self.name)))
412
407
        return ret
413
408
 
414
409
 
461
456
                          "fingerprint", "host", "interval",
462
457
                          "last_approval_request", "last_checked_ok",
463
458
                          "last_enabled", "name", "timeout")
464
 
    client_defaults = {
465
 
        "timeout": "PT5M",
466
 
        "extended_timeout": "PT15M",
467
 
        "interval": "PT2M",
468
 
        "checker": "fping -q -- %%(host)s",
469
 
        "host": "",
470
 
        "approval_delay": "PT0S",
471
 
        "approval_duration": "PT1S",
472
 
        "approved_by_default": "True",
473
 
        "enabled": "True",
474
 
    }
 
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
                        }
475
469
    
476
470
    @staticmethod
477
471
    def config_parser(config):
555
549
        self.current_checker_command = None
556
550
        self.approved = None
557
551
        self.approvals_pending = 0
558
 
        self.changedstate = multiprocessing_manager.Condition(
559
 
            multiprocessing_manager.Lock())
560
 
        self.client_structure = [attr
561
 
                                 for attr in self.__dict__.iterkeys()
 
552
        self.changedstate = (multiprocessing_manager
 
553
                             .Condition(multiprocessing_manager
 
554
                                        .Lock()))
 
555
        self.client_structure = [attr for attr in
 
556
                                 self.__dict__.iterkeys()
562
557
                                 if not attr.startswith("_")]
563
558
        self.client_structure.append("client_structure")
564
559
        
565
 
        for name, t in inspect.getmembers(
566
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
567
564
            if not name.startswith("_"):
568
565
                self.client_structure.append(name)
569
566
    
611
608
        # and every interval from then on.
612
609
        if self.checker_initiator_tag is not None:
613
610
            gobject.source_remove(self.checker_initiator_tag)
614
 
        self.checker_initiator_tag = gobject.timeout_add(
615
 
            int(self.interval.total_seconds() * 1000),
616
 
            self.start_checker)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
617
615
        # Schedule a disable() when 'timeout' has passed
618
616
        if self.disable_initiator_tag is not None:
619
617
            gobject.source_remove(self.disable_initiator_tag)
620
 
        self.disable_initiator_tag = gobject.timeout_add(
621
 
            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))
622
622
        # Also start a new checker *right now*.
623
623
        self.start_checker()
624
624
    
633
633
                            vars(self))
634
634
                self.checked_ok()
635
635
            else:
636
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
637
638
        else:
638
639
            self.last_checker_status = -1
639
640
            logger.warning("Checker for %(name)s crashed?",
653
654
            gobject.source_remove(self.disable_initiator_tag)
654
655
            self.disable_initiator_tag = None
655
656
        if getattr(self, "enabled", False):
656
 
            self.disable_initiator_tag = gobject.timeout_add(
657
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
658
660
            self.expires = datetime.datetime.utcnow() + timeout
659
661
    
660
662
    def need_approval(self):
691
693
        # Start a new checker if needed
692
694
        if self.checker is None:
693
695
            # Escape attributes for the shell
694
 
            escaped_attrs = {
695
 
                attr: re.escape(str(getattr(self, attr)))
696
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
697
699
            try:
698
700
                command = self.checker_command % escaped_attrs
699
701
            except TypeError as error:
700
702
                logger.error('Could not format string "%s"',
701
 
                             self.checker_command,
702
 
                             exc_info=error)
703
 
                return True     # Try again later
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
704
705
            self.current_checker_command = command
705
706
            try:
706
 
                logger.info("Starting checker %r for %s", command,
707
 
                            self.name)
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
708
709
                # We don't need to redirect stdout and stderr, since
709
710
                # in normal mode, that is already done by daemon(),
710
711
                # and in debug mode we don't want to.  (Stdin is
719
720
                                       "stderr": wnull })
720
721
                self.checker = subprocess.Popen(command,
721
722
                                                close_fds=True,
722
 
                                                shell=True,
723
 
                                                cwd="/",
 
723
                                                shell=True, cwd="/",
724
724
                                                **popen_args)
725
725
            except OSError as error:
726
726
                logger.error("Failed to start subprocess",
727
727
                             exc_info=error)
728
728
                return True
729
 
            self.checker_callback_tag = gobject.child_watch_add(
730
 
                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))
731
733
            # The checker may have completed before the gobject
732
734
            # watch was added.  Check for this.
733
735
            try:
764
766
        self.checker = None
765
767
 
766
768
 
767
 
def dbus_service_property(dbus_interface,
768
 
                          signature="v",
769
 
                          access="readwrite",
770
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
771
771
    """Decorators for marking methods of a DBusObjectWithProperties to
772
772
    become properties on the D-Bus.
773
773
    
783
783
    if byte_arrays and signature != "ay":
784
784
        raise ValueError("Byte arrays not supported for non-'ay'"
785
785
                         " signature {!r}".format(signature))
786
 
    
787
786
    def decorator(func):
788
787
        func._dbus_is_property = True
789
788
        func._dbus_interface = dbus_interface
794
793
            func._dbus_name = func._dbus_name[:-14]
795
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
796
795
        return func
797
 
    
798
796
    return decorator
799
797
 
800
798
 
809
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
810
808
                    "false"}
811
809
    """
812
 
    
813
810
    def decorator(func):
814
811
        func._dbus_is_interface = True
815
812
        func._dbus_interface = dbus_interface
816
813
        func._dbus_name = dbus_interface
817
814
        return func
818
 
    
819
815
    return decorator
820
816
 
821
817
 
831
827
    def Property_dbus_property(self):
832
828
        return dbus.Boolean(False)
833
829
    """
834
 
    
835
830
    def decorator(func):
836
831
        func._dbus_annotations = annotations
837
832
        return func
838
 
    
839
833
    return decorator
840
834
 
841
835
 
844
838
    """
845
839
    pass
846
840
 
847
 
 
848
841
class DBusPropertyAccessException(DBusPropertyException):
849
842
    """A property's access permissions disallows an operation.
850
843
    """
878
871
    def _get_all_dbus_things(self, thing):
879
872
        """Returns a generator of (name, attribute) pairs
880
873
        """
881
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
882
876
                 athing.__get__(self))
883
877
                for cls in self.__class__.__mro__
884
878
                for name, athing in
885
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
886
881
    
887
882
    def _get_dbus_property(self, interface_name, property_name):
888
883
        """Returns a bound method if one exists which is a D-Bus
889
884
        property with the specified name and interface.
890
885
        """
891
 
        for cls in self.__class__.__mro__:
892
 
            for name, value in inspect.getmembers(
893
 
                    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"))):
894
890
                if (value._dbus_name == property_name
895
891
                    and value._dbus_interface == interface_name):
896
892
                    return value.__get__(self)
897
893
        
898
894
        # No such property
899
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
900
 
            self.dbus_object_path, interface_name, property_name))
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
901
898
    
902
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
903
 
                         in_signature="ss",
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
904
900
                         out_signature="v")
905
901
    def Get(self, interface_name, property_name):
906
902
        """Standard D-Bus property Get() method, see D-Bus standard.
931
927
                                            for byte in value))
932
928
        prop(value)
933
929
    
934
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
935
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
936
931
                         out_signature="a{sv}")
937
932
    def GetAll(self, interface_name):
938
933
        """Standard D-Bus property GetAll() method, see D-Bus
953
948
            if not hasattr(value, "variant_level"):
954
949
                properties[name] = value
955
950
                continue
956
 
            properties[name] = type(value)(
957
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
958
953
        return dbus.Dictionary(properties, signature="sv")
959
954
    
960
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
978
973
                                                   connection)
979
974
        try:
980
975
            document = xml.dom.minidom.parseString(xmlstring)
981
 
            
982
976
            def make_tag(document, name, prop):
983
977
                e = document.createElement("property")
984
978
                e.setAttribute("name", name)
985
979
                e.setAttribute("type", prop._dbus_signature)
986
980
                e.setAttribute("access", prop._dbus_access)
987
981
                return e
988
 
            
989
982
            for if_tag in document.getElementsByTagName("interface"):
990
983
                # Add property tags
991
984
                for tag in (make_tag(document, name, prop)
1003
996
                            if (name == tag.getAttribute("name")
1004
997
                                and prop._dbus_interface
1005
998
                                == if_tag.getAttribute("name")):
1006
 
                                annots.update(getattr(
1007
 
                                    prop, "_dbus_annotations", {}))
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
1008
1003
                        for name, value in annots.items():
1009
1004
                            ann_tag = document.createElement(
1010
1005
                                "annotation")
1015
1010
                for annotation, value in dict(
1016
1011
                    itertools.chain.from_iterable(
1017
1012
                        annotations().items()
1018
 
                        for name, annotations
1019
 
                        in self._get_all_dbus_things("interface")
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
1020
1015
                        if name == if_tag.getAttribute("name")
1021
1016
                        )).items():
1022
1017
                    ann_tag = document.createElement("annotation")
1051
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1052
1047
    if dt is None:
1053
1048
        return dbus.String("", variant_level = variant_level)
1054
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1055
1051
 
1056
1052
 
1057
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1077
1073
    (from DBusObjectWithProperties) and interfaces (from the
1078
1074
    dbus_interface_annotations decorator).
1079
1075
    """
1080
 
    
1081
1076
    def wrapper(cls):
1082
1077
        for orig_interface_name, alt_interface_name in (
1083
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1084
1079
            attr = {}
1085
1080
            interface_names = set()
1086
1081
            # Go though all attributes of the class
1088
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1089
1084
                # with the wrong interface name
1090
1085
                if (not hasattr(attribute, "_dbus_interface")
1091
 
                    or not attribute._dbus_interface.startswith(
1092
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1093
1088
                    continue
1094
1089
                # Create an alternate D-Bus interface name based on
1095
1090
                # the current name
1096
 
                alt_interface = attribute._dbus_interface.replace(
1097
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1098
1094
                interface_names.add(alt_interface)
1099
1095
                # Is this a D-Bus signal?
1100
1096
                if getattr(attribute, "_dbus_is_signal", False):
1101
1097
                    # Extract the original non-method undecorated
1102
1098
                    # function by black magic
1103
1099
                    nonmethod_func = (dict(
1104
 
                        zip(attribute.func_code.co_freevars,
1105
 
                            attribute.__closure__))
1106
 
                                      ["func"].cell_contents)
 
1100
                            zip(attribute.func_code.co_freevars,
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1107
1103
                    # Create a new, but exactly alike, function
1108
1104
                    # object, and decorate it to be a new D-Bus signal
1109
1105
                    # with the alternate D-Bus interface name
1110
 
                    new_function = (dbus.service.signal(
1111
 
                        alt_interface, attribute._dbus_signature)
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
1112
1109
                                    (types.FunctionType(
1113
 
                                        nonmethod_func.func_code,
1114
 
                                        nonmethod_func.func_globals,
1115
 
                                        nonmethod_func.func_name,
1116
 
                                        nonmethod_func.func_defaults,
1117
 
                                        nonmethod_func.func_closure)))
 
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)))
1118
1115
                    # Copy annotations, if any
1119
1116
                    try:
1120
 
                        new_function._dbus_annotations = dict(
1121
 
                            attribute._dbus_annotations)
 
1117
                        new_function._dbus_annotations = (
 
1118
                            dict(attribute._dbus_annotations))
1122
1119
                    except AttributeError:
1123
1120
                        pass
1124
1121
                    # Define a creator of a function to call both the
1129
1126
                        """This function is a scope container to pass
1130
1127
                        func1 and func2 to the "call_both" function
1131
1128
                        outside of its arguments"""
1132
 
                        
1133
1129
                        def call_both(*args, **kwargs):
1134
1130
                            """This function will emit two D-Bus
1135
1131
                            signals by calling func1 and func2"""
1136
1132
                            func1(*args, **kwargs)
1137
1133
                            func2(*args, **kwargs)
1138
 
                        
1139
1134
                        return call_both
1140
1135
                    # Create the "call_both" function and add it to
1141
1136
                    # the class
1146
1141
                    # object.  Decorate it to be a new D-Bus method
1147
1142
                    # with the alternate D-Bus interface name.  Add it
1148
1143
                    # to the class.
1149
 
                    attr[attrname] = (
1150
 
                        dbus.service.method(
1151
 
                            alt_interface,
1152
 
                            attribute._dbus_in_signature,
1153
 
                            attribute._dbus_out_signature)
1154
 
                        (types.FunctionType(attribute.func_code,
1155
 
                                            attribute.func_globals,
1156
 
                                            attribute.func_name,
1157
 
                                            attribute.func_defaults,
1158
 
                                            attribute.func_closure)))
 
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)))
1159
1154
                    # Copy annotations, if any
1160
1155
                    try:
1161
 
                        attr[attrname]._dbus_annotations = dict(
1162
 
                            attribute._dbus_annotations)
 
1156
                        attr[attrname]._dbus_annotations = (
 
1157
                            dict(attribute._dbus_annotations))
1163
1158
                    except AttributeError:
1164
1159
                        pass
1165
1160
                # Is this a D-Bus property?
1168
1163
                    # object, and decorate it to be a new D-Bus
1169
1164
                    # property with the alternate D-Bus interface
1170
1165
                    # name.  Add it to the class.
1171
 
                    attr[attrname] = (dbus_service_property(
1172
 
                        alt_interface, attribute._dbus_signature,
1173
 
                        attribute._dbus_access,
1174
 
                        attribute._dbus_get_args_options
1175
 
                        ["byte_arrays"])
1176
 
                                      (types.FunctionType(
1177
 
                                          attribute.func_code,
1178
 
                                          attribute.func_globals,
1179
 
                                          attribute.func_name,
1180
 
                                          attribute.func_defaults,
1181
 
                                          attribute.func_closure)))
 
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)))
1182
1179
                    # Copy annotations, if any
1183
1180
                    try:
1184
 
                        attr[attrname]._dbus_annotations = dict(
1185
 
                            attribute._dbus_annotations)
 
1181
                        attr[attrname]._dbus_annotations = (
 
1182
                            dict(attribute._dbus_annotations))
1186
1183
                    except AttributeError:
1187
1184
                        pass
1188
1185
                # Is this a D-Bus interface?
1191
1188
                    # object.  Decorate it to be a new D-Bus interface
1192
1189
                    # with the alternate D-Bus interface name.  Add it
1193
1190
                    # to the class.
1194
 
                    attr[attrname] = (
1195
 
                        dbus_interface_annotations(alt_interface)
1196
 
                        (types.FunctionType(attribute.func_code,
1197
 
                                            attribute.func_globals,
1198
 
                                            attribute.func_name,
1199
 
                                            attribute.func_defaults,
1200
 
                                            attribute.func_closure)))
 
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)))
1201
1199
            if deprecate:
1202
1200
                # Deprecate all alternate interfaces
1203
1201
                iname="_AlternateDBusNames_interface_annotation{}"
1204
1202
                for interface_name in interface_names:
1205
 
                    
1206
1203
                    @dbus_interface_annotations(interface_name)
1207
1204
                    def func(self):
1208
1205
                        return { "org.freedesktop.DBus.Deprecated":
1209
 
                                 "true" }
 
1206
                                     "true" }
1210
1207
                    # Find an unused name
1211
1208
                    for aname in (iname.format(i)
1212
1209
                                  for i in itertools.count()):
1217
1214
                # Replace the class with a new subclass of it with
1218
1215
                # methods, signals, etc. as created above.
1219
1216
                cls = type(b"{}Alternate".format(cls.__name__),
1220
 
                           (cls, ), attr)
 
1217
                           (cls,), attr)
1221
1218
        return cls
1222
 
    
1223
1219
    return wrapper
1224
1220
 
1225
1221
 
1226
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1227
 
                            "se.bsnet.fukt.Mandos"})
 
1223
                                "se.bsnet.fukt.Mandos"})
1228
1224
class ClientDBus(Client, DBusObjectWithProperties):
1229
1225
    """A Client class using D-Bus
1230
1226
    
1234
1230
    """
1235
1231
    
1236
1232
    runtime_expansions = (Client.runtime_expansions
1237
 
                          + ("dbus_object_path", ))
 
1233
                          + ("dbus_object_path",))
1238
1234
    
1239
1235
    _interface = "se.recompile.Mandos.Client"
1240
1236
    
1248
1244
        client_object_name = str(self.name).translate(
1249
1245
            {ord("."): ord("_"),
1250
1246
             ord("-"): ord("_")})
1251
 
        self.dbus_object_path = dbus.ObjectPath(
1252
 
            "/clients/" + client_object_name)
 
1247
        self.dbus_object_path = (dbus.ObjectPath
 
1248
                                 ("/clients/" + client_object_name))
1253
1249
        DBusObjectWithProperties.__init__(self, self.bus,
1254
1250
                                          self.dbus_object_path)
1255
1251
    
1256
 
    def notifychangeproperty(transform_func, dbus_name,
1257
 
                             type_func=lambda x: x,
1258
 
                             variant_level=1,
1259
 
                             invalidate_only=False,
 
1252
    def notifychangeproperty(transform_func,
 
1253
                             dbus_name, type_func=lambda x: x,
 
1254
                             variant_level=1, invalidate_only=False,
1260
1255
                             _interface=_interface):
1261
1256
        """ Modify a variable so that it's a property which announces
1262
1257
        its changes to DBus.
1269
1264
        variant_level: D-Bus variant level.  Default: 1
1270
1265
        """
1271
1266
        attrname = "_{}".format(dbus_name)
1272
 
        
1273
1267
        def setter(self, value):
1274
1268
            if hasattr(self, "dbus_object_path"):
1275
1269
                if (not hasattr(self, attrname) or
1276
1270
                    type_func(getattr(self, attrname, None))
1277
1271
                    != type_func(value)):
1278
1272
                    if invalidate_only:
1279
 
                        self.PropertiesChanged(
1280
 
                            _interface, dbus.Dictionary(),
1281
 
                            dbus.Array((dbus_name, )))
 
1273
                        self.PropertiesChanged(_interface,
 
1274
                                               dbus.Dictionary(),
 
1275
                                               dbus.Array
 
1276
                                               ((dbus_name,)))
1282
1277
                    else:
1283
 
                        dbus_value = transform_func(
1284
 
                            type_func(value),
1285
 
                            variant_level = variant_level)
 
1278
                        dbus_value = transform_func(type_func(value),
 
1279
                                                    variant_level
 
1280
                                                    =variant_level)
1286
1281
                        self.PropertyChanged(dbus.String(dbus_name),
1287
1282
                                             dbus_value)
1288
 
                        self.PropertiesChanged(
1289
 
                            _interface,
1290
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1291
 
                                              dbus_value }),
1292
 
                            dbus.Array())
 
1283
                        self.PropertiesChanged(_interface,
 
1284
                                               dbus.Dictionary({
 
1285
                                    dbus.String(dbus_name):
 
1286
                                        dbus_value }), dbus.Array())
1293
1287
            setattr(self, attrname, value)
1294
1288
        
1295
1289
        return property(lambda self: getattr(self, attrname), setter)
1301
1295
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1302
1296
    last_enabled = notifychangeproperty(datetime_to_dbus,
1303
1297
                                        "LastEnabled")
1304
 
    checker = notifychangeproperty(
1305
 
        dbus.Boolean, "CheckerRunning",
1306
 
        type_func = lambda checker: checker is not None)
 
1298
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1299
                                   type_func = lambda checker:
 
1300
                                       checker is not None)
1307
1301
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1308
1302
                                           "LastCheckedOK")
1309
1303
    last_checker_status = notifychangeproperty(dbus.Int16,
1312
1306
        datetime_to_dbus, "LastApprovalRequest")
1313
1307
    approved_by_default = notifychangeproperty(dbus.Boolean,
1314
1308
                                               "ApprovedByDefault")
1315
 
    approval_delay = notifychangeproperty(
1316
 
        dbus.UInt64, "ApprovalDelay",
1317
 
        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)
1318
1314
    approval_duration = notifychangeproperty(
1319
1315
        dbus.UInt64, "ApprovalDuration",
1320
1316
        type_func = lambda td: td.total_seconds() * 1000)
1321
1317
    host = notifychangeproperty(dbus.String, "Host")
1322
 
    timeout = notifychangeproperty(
1323
 
        dbus.UInt64, "Timeout",
1324
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1318
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1319
                                   type_func = lambda td:
 
1320
                                       td.total_seconds() * 1000)
1325
1321
    extended_timeout = notifychangeproperty(
1326
1322
        dbus.UInt64, "ExtendedTimeout",
1327
1323
        type_func = lambda td: td.total_seconds() * 1000)
1328
 
    interval = notifychangeproperty(
1329
 
        dbus.UInt64, "Interval",
1330
 
        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)
1331
1329
    checker_command = notifychangeproperty(dbus.String, "Checker")
1332
1330
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1333
1331
                                  invalidate_only=True)
1471
1469
        return dbus.Boolean(bool(self.approvals_pending))
1472
1470
    
1473
1471
    # ApprovedByDefault - property
1474
 
    @dbus_service_property(_interface,
1475
 
                           signature="b",
 
1472
    @dbus_service_property(_interface, signature="b",
1476
1473
                           access="readwrite")
1477
1474
    def ApprovedByDefault_dbus_property(self, value=None):
1478
1475
        if value is None:       # get
1480
1477
        self.approved_by_default = bool(value)
1481
1478
    
1482
1479
    # ApprovalDelay - property
1483
 
    @dbus_service_property(_interface,
1484
 
                           signature="t",
 
1480
    @dbus_service_property(_interface, signature="t",
1485
1481
                           access="readwrite")
1486
1482
    def ApprovalDelay_dbus_property(self, value=None):
1487
1483
        if value is None:       # get
1490
1486
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1491
1487
    
1492
1488
    # ApprovalDuration - property
1493
 
    @dbus_service_property(_interface,
1494
 
                           signature="t",
 
1489
    @dbus_service_property(_interface, signature="t",
1495
1490
                           access="readwrite")
1496
1491
    def ApprovalDuration_dbus_property(self, value=None):
1497
1492
        if value is None:       # get
1510
1505
        return dbus.String(self.fingerprint)
1511
1506
    
1512
1507
    # Host - property
1513
 
    @dbus_service_property(_interface,
1514
 
                           signature="s",
 
1508
    @dbus_service_property(_interface, signature="s",
1515
1509
                           access="readwrite")
1516
1510
    def Host_dbus_property(self, value=None):
1517
1511
        if value is None:       # get
1529
1523
        return datetime_to_dbus(self.last_enabled)
1530
1524
    
1531
1525
    # Enabled - property
1532
 
    @dbus_service_property(_interface,
1533
 
                           signature="b",
 
1526
    @dbus_service_property(_interface, signature="b",
1534
1527
                           access="readwrite")
1535
1528
    def Enabled_dbus_property(self, value=None):
1536
1529
        if value is None:       # get
1541
1534
            self.disable()
1542
1535
    
1543
1536
    # LastCheckedOK - property
1544
 
    @dbus_service_property(_interface,
1545
 
                           signature="s",
 
1537
    @dbus_service_property(_interface, signature="s",
1546
1538
                           access="readwrite")
1547
1539
    def LastCheckedOK_dbus_property(self, value=None):
1548
1540
        if value is not None:
1551
1543
        return datetime_to_dbus(self.last_checked_ok)
1552
1544
    
1553
1545
    # LastCheckerStatus - property
1554
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1546
    @dbus_service_property(_interface, signature="n",
 
1547
                           access="read")
1555
1548
    def LastCheckerStatus_dbus_property(self):
1556
1549
        return dbus.Int16(self.last_checker_status)
1557
1550
    
1566
1559
        return datetime_to_dbus(self.last_approval_request)
1567
1560
    
1568
1561
    # Timeout - property
1569
 
    @dbus_service_property(_interface,
1570
 
                           signature="t",
 
1562
    @dbus_service_property(_interface, signature="t",
1571
1563
                           access="readwrite")
1572
1564
    def Timeout_dbus_property(self, value=None):
1573
1565
        if value is None:       # get
1586
1578
                    is None):
1587
1579
                    return
1588
1580
                gobject.source_remove(self.disable_initiator_tag)
1589
 
                self.disable_initiator_tag = gobject.timeout_add(
1590
 
                    int((self.expires - now).total_seconds() * 1000),
1591
 
                    self.disable)
 
1581
                self.disable_initiator_tag = (
 
1582
                    gobject.timeout_add(
 
1583
                        int((self.expires - now).total_seconds()
 
1584
                            * 1000), self.disable))
1592
1585
    
1593
1586
    # ExtendedTimeout - property
1594
 
    @dbus_service_property(_interface,
1595
 
                           signature="t",
 
1587
    @dbus_service_property(_interface, signature="t",
1596
1588
                           access="readwrite")
1597
1589
    def ExtendedTimeout_dbus_property(self, value=None):
1598
1590
        if value is None:       # get
1601
1593
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1602
1594
    
1603
1595
    # Interval - property
1604
 
    @dbus_service_property(_interface,
1605
 
                           signature="t",
 
1596
    @dbus_service_property(_interface, signature="t",
1606
1597
                           access="readwrite")
1607
1598
    def Interval_dbus_property(self, value=None):
1608
1599
        if value is None:       # get
1613
1604
        if self.enabled:
1614
1605
            # Reschedule checker run
1615
1606
            gobject.source_remove(self.checker_initiator_tag)
1616
 
            self.checker_initiator_tag = gobject.timeout_add(
1617
 
                value, self.start_checker)
1618
 
            self.start_checker() # Start one now, too
 
1607
            self.checker_initiator_tag = (gobject.timeout_add
 
1608
                                          (value, self.start_checker))
 
1609
            self.start_checker()    # Start one now, too
1619
1610
    
1620
1611
    # Checker - property
1621
 
    @dbus_service_property(_interface,
1622
 
                           signature="s",
 
1612
    @dbus_service_property(_interface, signature="s",
1623
1613
                           access="readwrite")
1624
1614
    def Checker_dbus_property(self, value=None):
1625
1615
        if value is None:       # get
1627
1617
        self.checker_command = str(value)
1628
1618
    
1629
1619
    # CheckerRunning - property
1630
 
    @dbus_service_property(_interface,
1631
 
                           signature="b",
 
1620
    @dbus_service_property(_interface, signature="b",
1632
1621
                           access="readwrite")
1633
1622
    def CheckerRunning_dbus_property(self, value=None):
1634
1623
        if value is None:       # get
1644
1633
        return self.dbus_object_path # is already a dbus.ObjectPath
1645
1634
    
1646
1635
    # Secret = property
1647
 
    @dbus_service_property(_interface,
1648
 
                           signature="ay",
1649
 
                           access="write",
1650
 
                           byte_arrays=True)
 
1636
    @dbus_service_property(_interface, signature="ay",
 
1637
                           access="write", byte_arrays=True)
1651
1638
    def Secret_dbus_property(self, value):
1652
1639
        self.secret = bytes(value)
1653
1640
    
1669
1656
        if data[0] == 'data':
1670
1657
            return data[1]
1671
1658
        if data[0] == 'function':
1672
 
            
1673
1659
            def func(*args, **kwargs):
1674
1660
                self._pipe.send(('funcall', name, args, kwargs))
1675
1661
                return self._pipe.recv()[1]
1676
 
            
1677
1662
            return func
1678
1663
    
1679
1664
    def __setattr__(self, name, value):
1695
1680
            logger.debug("Pipe FD: %d",
1696
1681
                         self.server.child_pipe.fileno())
1697
1682
            
1698
 
            session = gnutls.connection.ClientSession(
1699
 
                self.request, gnutls.connection .X509Credentials())
 
1683
            session = (gnutls.connection
 
1684
                       .ClientSession(self.request,
 
1685
                                      gnutls.connection
 
1686
                                      .X509Credentials()))
1700
1687
            
1701
1688
            # Note: gnutls.connection.X509Credentials is really a
1702
1689
            # generic GnuTLS certificate credentials object so long as
1711
1698
            priority = self.server.gnutls_priority
1712
1699
            if priority is None:
1713
1700
                priority = "NORMAL"
1714
 
            gnutls.library.functions.gnutls_priority_set_direct(
1715
 
                session._c_object, priority, None)
 
1701
            (gnutls.library.functions
 
1702
             .gnutls_priority_set_direct(session._c_object,
 
1703
                                         priority, None))
1716
1704
            
1717
1705
            # Start communication using the Mandos protocol
1718
1706
            # Get protocol number
1738
1726
            approval_required = False
1739
1727
            try:
1740
1728
                try:
1741
 
                    fpr = self.fingerprint(
1742
 
                        self.peer_certificate(session))
 
1729
                    fpr = self.fingerprint(self.peer_certificate
 
1730
                                           (session))
1743
1731
                except (TypeError,
1744
1732
                        gnutls.errors.GNUTLSError) as error:
1745
1733
                    logger.warning("Bad certificate: %s", error)
1760
1748
                while True:
1761
1749
                    if not client.enabled:
1762
1750
                        logger.info("Client %s is disabled",
1763
 
                                    client.name)
 
1751
                                       client.name)
1764
1752
                        if self.server.use_dbus:
1765
1753
                            # Emit D-Bus signal
1766
1754
                            client.Rejected("Disabled")
1813
1801
                        logger.warning("gnutls send failed",
1814
1802
                                       exc_info=error)
1815
1803
                        return
1816
 
                    logger.debug("Sent: %d, remaining: %d", sent,
1817
 
                                 len(client.secret) - (sent_size
1818
 
                                                       + sent))
 
1804
                    logger.debug("Sent: %d, remaining: %d",
 
1805
                                 sent, len(client.secret)
 
1806
                                 - (sent_size + sent))
1819
1807
                    sent_size += sent
1820
1808
                
1821
1809
                logger.info("Sending secret to %s", client.name)
1838
1826
    def peer_certificate(session):
1839
1827
        "Return the peer's OpenPGP certificate as a bytestring"
1840
1828
        # If not an OpenPGP certificate...
1841
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1842
 
                session._c_object)
 
1829
        if (gnutls.library.functions
 
1830
            .gnutls_certificate_type_get(session._c_object)
1843
1831
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1844
1832
            # ...do the normal thing
1845
1833
            return session.peer_certificate
1859
1847
    def fingerprint(openpgp):
1860
1848
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1861
1849
        # New GnuTLS "datum" with the OpenPGP public key
1862
 
        datum = gnutls.library.types.gnutls_datum_t(
1863
 
            ctypes.cast(ctypes.c_char_p(openpgp),
1864
 
                        ctypes.POINTER(ctypes.c_ubyte)),
1865
 
            ctypes.c_uint(len(openpgp)))
 
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))))
1866
1855
        # New empty GnuTLS certificate
1867
1856
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1868
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1869
 
            ctypes.byref(crt))
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1870
1859
        # Import the OpenPGP public key into the certificate
1871
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1872
 
            crt, ctypes.byref(datum),
1873
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1860
        (gnutls.library.functions
 
1861
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1862
                                    gnutls.library.constants
 
1863
                                    .GNUTLS_OPENPGP_FMT_RAW))
1874
1864
        # Verify the self signature in the key
1875
1865
        crtverify = ctypes.c_uint()
1876
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1877
 
            crt, 0, ctypes.byref(crtverify))
 
1866
        (gnutls.library.functions
 
1867
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1868
                                         ctypes.byref(crtverify)))
1878
1869
        if crtverify.value != 0:
1879
1870
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1880
 
            raise gnutls.errors.CertificateSecurityError(
1881
 
                "Verify failed")
 
1871
            raise (gnutls.errors.CertificateSecurityError
 
1872
                   ("Verify failed"))
1882
1873
        # New buffer for the fingerprint
1883
1874
        buf = ctypes.create_string_buffer(20)
1884
1875
        buf_len = ctypes.c_size_t()
1885
1876
        # Get the fingerprint from the certificate into the buffer
1886
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1887
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1877
        (gnutls.library.functions
 
1878
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1879
                                             ctypes.byref(buf_len)))
1888
1880
        # Deinit the certificate
1889
1881
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1890
1882
        # Convert the buffer to a Python bytestring
1896
1888
 
1897
1889
class MultiprocessingMixIn(object):
1898
1890
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1899
 
    
1900
1891
    def sub_process_main(self, request, address):
1901
1892
        try:
1902
1893
            self.finish_request(request, address)
1914
1905
 
1915
1906
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1916
1907
    """ adds a pipe to the MixIn """
1917
 
    
1918
1908
    def process_request(self, request, client_address):
1919
1909
        """Overrides and wraps the original process_request().
1920
1910
        
1941
1931
        interface:      None or a network interface name (string)
1942
1932
        use_ipv6:       Boolean; to use IPv6 or not
1943
1933
    """
1944
 
    
1945
1934
    def __init__(self, server_address, RequestHandlerClass,
1946
 
                 interface=None,
1947
 
                 use_ipv6=True,
1948
 
                 socketfd=None):
 
1935
                 interface=None, use_ipv6=True, socketfd=None):
1949
1936
        """If socketfd is set, use that file descriptor instead of
1950
1937
        creating a new one with socket.socket().
1951
1938
        """
1992
1979
                             self.interface)
1993
1980
            else:
1994
1981
                try:
1995
 
                    self.socket.setsockopt(
1996
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
1997
 
                        (self.interface + "\0").encode("utf-8"))
 
1982
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1983
                                           SO_BINDTODEVICE,
 
1984
                                           (self.interface + "\0")
 
1985
                                           .encode("utf-8"))
1998
1986
                except socket.error as error:
1999
1987
                    if error.errno == errno.EPERM:
2000
1988
                        logger.error("No permission to bind to"
2018
2006
                self.server_address = (any_address,
2019
2007
                                       self.server_address[1])
2020
2008
            elif not self.server_address[1]:
2021
 
                self.server_address = (self.server_address[0], 0)
 
2009
                self.server_address = (self.server_address[0],
 
2010
                                       0)
2022
2011
#                 if self.interface:
2023
2012
#                     self.server_address = (self.server_address[0],
2024
2013
#                                            0, # port
2038
2027
    
2039
2028
    Assumes a gobject.MainLoop event loop.
2040
2029
    """
2041
 
    
2042
2030
    def __init__(self, server_address, RequestHandlerClass,
2043
 
                 interface=None,
2044
 
                 use_ipv6=True,
2045
 
                 clients=None,
2046
 
                 gnutls_priority=None,
2047
 
                 use_dbus=True,
2048
 
                 socketfd=None):
 
2031
                 interface=None, use_ipv6=True, clients=None,
 
2032
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2049
2033
        self.enabled = False
2050
2034
        self.clients = clients
2051
2035
        if self.clients is None:
2057
2041
                                interface = interface,
2058
2042
                                use_ipv6 = use_ipv6,
2059
2043
                                socketfd = socketfd)
2060
 
    
2061
2044
    def server_activate(self):
2062
2045
        if self.enabled:
2063
2046
            return socketserver.TCPServer.server_activate(self)
2067
2050
    
2068
2051
    def add_pipe(self, parent_pipe, proc):
2069
2052
        # Call "handle_ipc" for both data and EOF events
2070
 
        gobject.io_add_watch(
2071
 
            parent_pipe.fileno(),
2072
 
            gobject.IO_IN | gobject.IO_HUP,
2073
 
            functools.partial(self.handle_ipc,
2074
 
                              parent_pipe = parent_pipe,
2075
 
                              proc = proc))
 
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))
2076
2059
    
2077
 
    def handle_ipc(self, source, condition,
2078
 
                   parent_pipe=None,
2079
 
                   proc = None,
2080
 
                   client_object=None):
 
2060
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2061
                   proc = None, client_object=None):
2081
2062
        # error, or the other end of multiprocessing.Pipe has closed
2082
2063
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2083
2064
            # Wait for other process to exit
2106
2087
                parent_pipe.send(False)
2107
2088
                return False
2108
2089
            
2109
 
            gobject.io_add_watch(
2110
 
                parent_pipe.fileno(),
2111
 
                gobject.IO_IN | gobject.IO_HUP,
2112
 
                functools.partial(self.handle_ipc,
2113
 
                                  parent_pipe = parent_pipe,
2114
 
                                  proc = proc,
2115
 
                                  client_object = client))
 
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))
2116
2098
            parent_pipe.send(True)
2117
2099
            # remove the old hook in favor of the new above hook on
2118
2100
            # same fileno
2124
2106
            
2125
2107
            parent_pipe.send(('data', getattr(client_object,
2126
2108
                                              funcname)(*args,
2127
 
                                                        **kwargs)))
 
2109
                                                         **kwargs)))
2128
2110
        
2129
2111
        if command == 'getattr':
2130
2112
            attrname = request[1]
2131
2113
            if callable(client_object.__getattribute__(attrname)):
2132
 
                parent_pipe.send(('function', ))
 
2114
                parent_pipe.send(('function',))
2133
2115
            else:
2134
 
                parent_pipe.send((
2135
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2136
2118
        
2137
2119
        if command == 'setattr':
2138
2120
            attrname = request[1]
2178
2160
                                              # None
2179
2161
                                    "followers")) # Tokens valid after
2180
2162
                                                  # this token
2181
 
    Token = collections.namedtuple("Token", (
2182
 
        "regexp",  # To match token; if "value" is not None, must have
2183
 
                   # a "group" containing digits
2184
 
        "value",   # datetime.timedelta or None
2185
 
        "followers"))           # Tokens valid after this token
2186
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2187
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2188
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2189
2166
    token_second = Token(re.compile(r"(\d+)S"),
2190
2167
                         datetime.timedelta(seconds=1),
2191
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2192
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2193
2170
                         datetime.timedelta(minutes=1),
2194
2171
                         frozenset((token_second, token_end)))
2210
2187
                       frozenset((token_month, token_end)))
2211
2188
    token_week = Token(re.compile(r"(\d+)W"),
2212
2189
                       datetime.timedelta(weeks=1),
2213
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2214
2191
    token_duration = Token(re.compile(r"P"), None,
2215
2192
                           frozenset((token_year, token_month,
2216
2193
                                      token_day, token_time,
2284
2261
            elif suffix == "w":
2285
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2286
2263
            else:
2287
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2288
2266
        except IndexError as e:
2289
2267
            raise ValueError(*(e.args))
2290
2268
        timevalue += delta
2306
2284
        # Close all standard open file descriptors
2307
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2308
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2309
 
            raise OSError(errno.ENODEV,
2310
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2311
2288
                          .format(os.devnull))
2312
2289
        os.dup2(null, sys.stdin.fileno())
2313
2290
        os.dup2(null, sys.stdout.fileno())
2390
2367
                        "statedir": "/var/lib/mandos",
2391
2368
                        "foreground": "False",
2392
2369
                        "zeroconf": "True",
2393
 
                    }
 
2370
                        }
2394
2371
    
2395
2372
    # Parse config file for server-global settings
2396
2373
    server_config = configparser.SafeConfigParser(server_defaults)
2397
2374
    del server_defaults
2398
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2375
    server_config.read(os.path.join(options.configdir,
 
2376
                                    "mandos.conf"))
2399
2377
    # Convert the SafeConfigParser object to a dict
2400
2378
    server_settings = server_config.defaults()
2401
2379
    # Use the appropriate methods on the non-string config options
2419
2397
    # Override the settings from the config file with command line
2420
2398
    # options, if set.
2421
2399
    for option in ("interface", "address", "port", "debug",
2422
 
                   "priority", "servicename", "configdir", "use_dbus",
2423
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2424
 
                   "socket", "foreground", "zeroconf"):
 
2400
                   "priority", "servicename", "configdir",
 
2401
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2402
                   "statedir", "socket", "foreground", "zeroconf"):
2425
2403
        value = getattr(options, option)
2426
2404
        if value is not None:
2427
2405
            server_settings[option] = value
2442
2420
    
2443
2421
    ##################################################################
2444
2422
    
2445
 
    if (not server_settings["zeroconf"]
2446
 
        and not (server_settings["port"]
2447
 
                 or server_settings["socket"] != "")):
2448
 
        parser.error("Needs port or socket to work without Zeroconf")
 
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")
2449
2428
    
2450
2429
    # For convenience
2451
2430
    debug = server_settings["debug"]
2467
2446
            initlogger(debug, level)
2468
2447
    
2469
2448
    if server_settings["servicename"] != "Mandos":
2470
 
        syslogger.setFormatter(
2471
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2472
 
                              ' %(levelname)s: %(message)s'.format(
2473
 
                                  server_settings["servicename"])))
 
2449
        syslogger.setFormatter(logging.Formatter
 
2450
                               ('Mandos ({}) [%(process)d]:'
 
2451
                                ' %(levelname)s: %(message)s'
 
2452
                                .format(server_settings
 
2453
                                        ["servicename"])))
2474
2454
    
2475
2455
    # Parse config file with clients
2476
2456
    client_config = configparser.SafeConfigParser(Client
2484
2464
    socketfd = None
2485
2465
    if server_settings["socket"] != "":
2486
2466
        socketfd = server_settings["socket"]
2487
 
    tcp_server = MandosServer(
2488
 
        (server_settings["address"], server_settings["port"]),
2489
 
        ClientHandler,
2490
 
        interface=(server_settings["interface"] or None),
2491
 
        use_ipv6=use_ipv6,
2492
 
        gnutls_priority=server_settings["priority"],
2493
 
        use_dbus=use_dbus,
2494
 
        socketfd=socketfd)
 
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)
2495
2477
    if not foreground:
2496
2478
        pidfilename = "/run/mandos.pid"
2497
2479
        if not os.path.isdir("/run/."):
2531
2513
        def debug_gnutls(level, string):
2532
2514
            logger.debug("GnuTLS: %s", string[:-1])
2533
2515
        
2534
 
        gnutls.library.functions.gnutls_global_set_log_function(
2535
 
            debug_gnutls)
 
2516
        (gnutls.library.functions
 
2517
         .gnutls_global_set_log_function(debug_gnutls))
2536
2518
        
2537
2519
        # Redirect stdin so all checkers get /dev/null
2538
2520
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2558
2540
    if use_dbus:
2559
2541
        try:
2560
2542
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2561
 
                                            bus,
2562
 
                                            do_not_queue=True)
2563
 
            old_bus_name = dbus.service.BusName(
2564
 
                "se.bsnet.fukt.Mandos", bus,
2565
 
                do_not_queue=True)
 
2543
                                            bus, do_not_queue=True)
 
2544
            old_bus_name = (dbus.service.BusName
 
2545
                            ("se.bsnet.fukt.Mandos", bus,
 
2546
                             do_not_queue=True))
2566
2547
        except dbus.exceptions.NameExistsException as e:
2567
2548
            logger.error("Disabling D-Bus:", exc_info=e)
2568
2549
            use_dbus = False
2570
2551
            tcp_server.use_dbus = False
2571
2552
    if zeroconf:
2572
2553
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2573
 
        service = AvahiServiceToSyslog(
2574
 
            name = server_settings["servicename"],
2575
 
            servicetype = "_mandos._tcp",
2576
 
            protocol = protocol,
2577
 
            bus = bus)
 
2554
        service = AvahiServiceToSyslog(name =
 
2555
                                       server_settings["servicename"],
 
2556
                                       servicetype = "_mandos._tcp",
 
2557
                                       protocol = protocol, bus = bus)
2578
2558
        if server_settings["interface"]:
2579
 
            service.interface = if_nametoindex(
2580
 
                server_settings["interface"].encode("utf-8"))
 
2559
            service.interface = (if_nametoindex
 
2560
                                 (server_settings["interface"]
 
2561
                                  .encode("utf-8")))
2581
2562
    
2582
2563
    global multiprocessing_manager
2583
2564
    multiprocessing_manager = multiprocessing.Manager()
2602
2583
    if server_settings["restore"]:
2603
2584
        try:
2604
2585
            with open(stored_state_path, "rb") as stored_state:
2605
 
                clients_data, old_client_settings = pickle.load(
2606
 
                    stored_state)
 
2586
                clients_data, old_client_settings = (pickle.load
 
2587
                                                     (stored_state))
2607
2588
            os.remove(stored_state_path)
2608
2589
        except IOError as e:
2609
2590
            if e.errno == errno.ENOENT:
2610
 
                logger.warning("Could not load persistent state:"
2611
 
                               " {}".format(os.strerror(e.errno)))
 
2591
                logger.warning("Could not load persistent state: {}"
 
2592
                                .format(os.strerror(e.errno)))
2612
2593
            else:
2613
2594
                logger.critical("Could not load persistent state:",
2614
2595
                                exc_info=e)
2615
2596
                raise
2616
2597
        except EOFError as e:
2617
2598
            logger.warning("Could not load persistent state: "
2618
 
                           "EOFError:",
2619
 
                           exc_info=e)
 
2599
                           "EOFError:", exc_info=e)
2620
2600
    
2621
2601
    with PGPEngine() as pgp:
2622
2602
        for client_name, client in clients_data.items():
2634
2614
                    # For each value in new config, check if it
2635
2615
                    # differs from the old config value (Except for
2636
2616
                    # the "secret" attribute)
2637
 
                    if (name != "secret"
2638
 
                        and (value !=
2639
 
                             old_client_settings[client_name][name])):
 
2617
                    if (name != "secret" and
 
2618
                        value != old_client_settings[client_name]
 
2619
                        [name]):
2640
2620
                        client[name] = value
2641
2621
                except KeyError:
2642
2622
                    pass
2651
2631
                    if not client["last_checked_ok"]:
2652
2632
                        logger.warning(
2653
2633
                            "disabling client {} - Client never "
2654
 
                            "performed a successful checker".format(
2655
 
                                client_name))
 
2634
                            "performed a successful checker"
 
2635
                            .format(client_name))
2656
2636
                        client["enabled"] = False
2657
2637
                    elif client["last_checker_status"] != 0:
2658
2638
                        logger.warning(
2659
2639
                            "disabling client {} - Client last"
2660
 
                            " checker failed with error code"
2661
 
                            " {}".format(
2662
 
                                client_name,
2663
 
                                client["last_checker_status"]))
 
2640
                            " checker failed with error code {}"
 
2641
                            .format(client_name,
 
2642
                                    client["last_checker_status"]))
2664
2643
                        client["enabled"] = False
2665
2644
                    else:
2666
 
                        client["expires"] = (
2667
 
                            datetime.datetime.utcnow()
2668
 
                            + client["timeout"])
 
2645
                        client["expires"] = (datetime.datetime
 
2646
                                             .utcnow()
 
2647
                                             + client["timeout"])
2669
2648
                        logger.debug("Last checker succeeded,"
2670
 
                                     " keeping {} enabled".format(
2671
 
                                         client_name))
 
2649
                                     " keeping {} enabled"
 
2650
                                     .format(client_name))
2672
2651
            try:
2673
 
                client["secret"] = pgp.decrypt(
2674
 
                    client["encrypted_secret"],
2675
 
                    client_settings[client_name]["secret"])
 
2652
                client["secret"] = (
 
2653
                    pgp.decrypt(client["encrypted_secret"],
 
2654
                                client_settings[client_name]
 
2655
                                ["secret"]))
2676
2656
            except PGPError:
2677
2657
                # If decryption fails, we use secret from new settings
2678
 
                logger.debug("Failed to decrypt {} old secret".format(
2679
 
                    client_name))
2680
 
                client["secret"] = (client_settings[client_name]
2681
 
                                    ["secret"])
 
2658
                logger.debug("Failed to decrypt {} old secret"
 
2659
                             .format(client_name))
 
2660
                client["secret"] = (
 
2661
                    client_settings[client_name]["secret"])
2682
2662
    
2683
2663
    # Add/remove clients based on new changes made to config
2684
2664
    for client_name in (set(old_client_settings)
2691
2671
    # Create all client objects
2692
2672
    for client_name, client in clients_data.items():
2693
2673
        tcp_server.clients[client_name] = client_class(
2694
 
            name = client_name,
2695
 
            settings = client,
 
2674
            name = client_name, settings = client,
2696
2675
            server_settings = server_settings)
2697
2676
    
2698
2677
    if not tcp_server.clients:
2714
2693
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2715
2694
    
2716
2695
    if use_dbus:
2717
 
        
2718
 
        @alternate_dbus_interfaces(
2719
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2696
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2697
                                        "se.bsnet.fukt.Mandos"})
2720
2698
        class MandosDBusService(DBusObjectWithProperties):
2721
2699
            """A D-Bus proxy object"""
2722
 
            
2723
2700
            def __init__(self):
2724
2701
                dbus.service.Object.__init__(self, bus, "/")
2725
 
            
2726
2702
            _interface = "se.recompile.Mandos"
2727
2703
            
2728
2704
            @dbus_interface_annotations(_interface)
2729
2705
            def _foo(self):
2730
 
                return {
2731
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2732
 
                    "false" }
 
2706
                return { "org.freedesktop.DBus.Property"
 
2707
                         ".EmitsChangedSignal":
 
2708
                             "false"}
2733
2709
            
2734
2710
            @dbus.service.signal(_interface, signature="o")
2735
2711
            def ClientAdded(self, objpath):
2749
2725
            @dbus.service.method(_interface, out_signature="ao")
2750
2726
            def GetAllClients(self):
2751
2727
                "D-Bus method"
2752
 
                return dbus.Array(c.dbus_object_path for c in
 
2728
                return dbus.Array(c.dbus_object_path
 
2729
                                  for c in
2753
2730
                                  tcp_server.clients.itervalues())
2754
2731
            
2755
2732
            @dbus.service.method(_interface,
2804
2781
                # + secret.
2805
2782
                exclude = { "bus", "changedstate", "secret",
2806
2783
                            "checker", "server_settings" }
2807
 
                for name, typ in inspect.getmembers(dbus.service
2808
 
                                                    .Object):
 
2784
                for name, typ in (inspect.getmembers
 
2785
                                  (dbus.service.Object)):
2809
2786
                    exclude.add(name)
2810
2787
                
2811
2788
                client_dict["encrypted_secret"] = (client
2818
2795
                del client_settings[client.name]["secret"]
2819
2796
        
2820
2797
        try:
2821
 
            with tempfile.NamedTemporaryFile(
2822
 
                    mode='wb',
2823
 
                    suffix=".pickle",
2824
 
                    prefix='clients-',
2825
 
                    dir=os.path.dirname(stored_state_path),
2826
 
                    delete=False) as stored_state:
 
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:
2827
2802
                pickle.dump((clients, client_settings), stored_state)
2828
 
                tempname = stored_state.name
 
2803
                tempname=stored_state.name
2829
2804
            os.rename(tempname, stored_state_path)
2830
2805
        except (IOError, OSError) as e:
2831
2806
            if not debug:
2850
2825
            client.disable(quiet=True)
2851
2826
            if use_dbus:
2852
2827
                # Emit D-Bus signal
2853
 
                mandos_dbus_service.ClientRemoved(
2854
 
                    client.dbus_object_path, client.name)
 
2828
                mandos_dbus_service.ClientRemoved(client
 
2829
                                                  .dbus_object_path,
 
2830
                                                  client.name)
2855
2831
        client_settings.clear()
2856
2832
    
2857
2833
    atexit.register(cleanup)
2910
2886
    # Must run before the D-Bus bus name gets deregistered
2911
2887
    cleanup()
2912
2888
 
2913
 
 
2914
2889
if __name__ == '__main__':
2915
2890
    main()