/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: 2022-04-23 23:58:39 UTC
  • Revision ID: teddy@recompile.se-20220423235839-cnt9aq1kjveqaydc
Bug fix in mandos-ctl: handle backslashes in password

* mandos-ctl (mode=password): When sending the password to gpg, use
  "printf" instead of "echo -n".  This avoids the behavior of the
  "echo" builtin in "dash", which always interprets backslash escape
  codes.

Reported-By: Jesse Norell <jesse@kci.net>

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-2019 Teddy Hogeborn
15
 
# Copyright © 2008-2019 Björn Påhlsson
 
14
# Copyright © 2008-2020 Teddy Hogeborn
 
15
# Copyright © 2008-2020 Björn Påhlsson
16
16
#
17
17
# This file is part of Mandos.
18
18
#
79
79
import codecs
80
80
import unittest
81
81
import random
 
82
import shlex
82
83
 
83
84
import dbus
84
85
import dbus.service
94
95
    __metaclass__ = type
95
96
    str = unicode
96
97
 
 
98
# Add collections.abc.Callable if it does not exist
 
99
try:
 
100
    collections.abc.Callable
 
101
except AttributeError:
 
102
    class abc:
 
103
        Callable = collections.Callable
 
104
    collections.abc = abc
 
105
    del abc
 
106
 
 
107
# Add shlex.quote if it does not exist
 
108
try:
 
109
    shlex.quote
 
110
except AttributeError:
 
111
    shlex.quote = re.escape
 
112
 
97
113
# Show warnings by default
98
114
if not sys.warnoptions:
99
115
    import warnings
127
143
if sys.version_info < (3, 2):
128
144
    configparser.Configparser = configparser.SafeConfigParser
129
145
 
130
 
version = "1.8.9"
 
146
version = "1.8.14"
131
147
stored_state_file = "clients.pickle"
132
148
 
133
149
logger = logging.getLogger()
173
189
        facility=logging.handlers.SysLogHandler.LOG_DAEMON,
174
190
        address="/dev/log"))
175
191
    syslogger.setFormatter(logging.Formatter
176
 
                           ('Mandos [%(process)d]: %(levelname)s:'
177
 
                            ' %(message)s'))
 
192
                           ("Mandos [%(process)d]: %(levelname)s:"
 
193
                            " %(message)s"))
178
194
    logger.addHandler(syslogger)
179
195
 
180
196
    if debug:
181
197
        console = logging.StreamHandler()
182
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
183
 
                                               ' [%(process)d]:'
184
 
                                               ' %(levelname)s:'
185
 
                                               ' %(message)s'))
 
198
        console.setFormatter(logging.Formatter("%(asctime)s %(name)s"
 
199
                                               " [%(process)d]:"
 
200
                                               " %(levelname)s:"
 
201
                                               " %(message)s"))
186
202
        logger.addHandler(console)
187
203
    logger.setLevel(level)
188
204
 
208
224
        except OSError as e:
209
225
            if e.errno != errno.ENOENT:
210
226
                raise
211
 
        self.gnupgargs = ['--batch',
212
 
                          '--homedir', self.tempdir,
213
 
                          '--force-mdc',
214
 
                          '--quiet']
 
227
        self.gnupgargs = ["--batch",
 
228
                          "--homedir", self.tempdir,
 
229
                          "--force-mdc",
 
230
                          "--quiet"]
215
231
        # Only GPG version 1 has the --no-use-agent option.
216
232
        if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
217
233
            self.gnupgargs.append("--no-use-agent")
256
272
                dir=self.tempdir) as passfile:
257
273
            passfile.write(passphrase)
258
274
            passfile.flush()
259
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
260
 
                                     '--passphrase-file',
 
275
            proc = subprocess.Popen([self.gpg, "--symmetric",
 
276
                                     "--passphrase-file",
261
277
                                     passfile.name]
262
278
                                    + self.gnupgargs,
263
279
                                    stdin=subprocess.PIPE,
274
290
                dir=self.tempdir) as passfile:
275
291
            passfile.write(passphrase)
276
292
            passfile.flush()
277
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
278
 
                                     '--passphrase-file',
 
293
            proc = subprocess.Popen([self.gpg, "--decrypt",
 
294
                                     "--passphrase-file",
279
295
                                     passfile.name]
280
296
                                    + self.gnupgargs,
281
297
                                    stdin=subprocess.PIPE,
334
350
    Attributes:
335
351
    interface: integer; avahi.IF_UNSPEC or an interface index.
336
352
               Used to optionally bind to the specified interface.
337
 
    name: string; Example: 'Mandos'
338
 
    type: string; Example: '_mandos._tcp'.
 
353
    name: string; Example: "Mandos"
 
354
    type: string; Example: "_mandos._tcp".
339
355
     See <https://www.iana.org/assignments/service-names-port-numbers>
340
356
    port: integer; what port to announce
341
357
    TXT: list of strings; TXT record for the service
419
435
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
420
436
        self.entry_group_state_changed_match = (
421
437
            self.group.connect_to_signal(
422
 
                'StateChanged', self.entry_group_state_changed))
 
438
                "StateChanged", self.entry_group_state_changed))
423
439
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
424
440
                     self.name, self.type)
425
441
        self.group.AddService(
508
524
class AvahiServiceToSyslog(AvahiService):
509
525
    def rename(self, *args, **kwargs):
510
526
        """Add the new name to the syslog messages"""
511
 
        ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
 
527
        ret = super(AvahiServiceToSyslog, self).rename(*args,
 
528
                                                       **kwargs)
512
529
        syslogger.setFormatter(logging.Formatter(
513
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
 
530
            "Mandos ({}) [%(process)d]: %(levelname)s: %(message)s"
514
531
            .format(self.name)))
515
532
        return ret
516
533
 
546
563
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
547
564
 
548
565
    # Types
549
 
    class session_int(ctypes.Structure):
 
566
    class _session_int(ctypes.Structure):
550
567
        _fields_ = []
551
 
    session_t = ctypes.POINTER(session_int)
 
568
    session_t = ctypes.POINTER(_session_int)
552
569
 
553
570
    class certificate_credentials_st(ctypes.Structure):
554
571
        _fields_ = []
557
574
    certificate_type_t = ctypes.c_int
558
575
 
559
576
    class datum_t(ctypes.Structure):
560
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
561
 
                    ('size', ctypes.c_uint)]
 
577
        _fields_ = [("data", ctypes.POINTER(ctypes.c_ubyte)),
 
578
                    ("size", ctypes.c_uint)]
562
579
 
563
 
    class openpgp_crt_int(ctypes.Structure):
 
580
    class _openpgp_crt_int(ctypes.Structure):
564
581
        _fields_ = []
565
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
 
582
    openpgp_crt_t = ctypes.POINTER(_openpgp_crt_int)
566
583
    openpgp_crt_fmt_t = ctypes.c_int  # gnutls/openpgp.h
567
584
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
568
585
    credentials_type_t = ctypes.c_int
577
594
            # gnutls.strerror()
578
595
            self.code = code
579
596
            if message is None and code is not None:
580
 
                message = gnutls.strerror(code)
 
597
                message = gnutls.strerror(code).decode(
 
598
                    "utf-8", errors="replace")
581
599
            return super(gnutls.Error, self).__init__(
582
600
                message, *args)
583
601
 
584
602
    class CertificateSecurityError(Error):
585
603
        pass
586
604
 
 
605
    class PointerTo:
 
606
        def __init__(self, cls):
 
607
            self.cls = cls
 
608
 
 
609
        def from_param(self, obj):
 
610
            if not isinstance(obj, self.cls):
 
611
                raise TypeError("Not of type {}: {!r}"
 
612
                                .format(self.cls.__name__, obj))
 
613
            return ctypes.byref(obj.from_param(obj))
 
614
 
 
615
    class CastToVoidPointer:
 
616
        def __init__(self, cls):
 
617
            self.cls = cls
 
618
 
 
619
        def from_param(self, obj):
 
620
            if not isinstance(obj, self.cls):
 
621
                raise TypeError("Not of type {}: {!r}"
 
622
                                .format(self.cls.__name__, obj))
 
623
            return ctypes.cast(obj.from_param(obj), ctypes.c_void_p)
 
624
 
 
625
    class With_from_param:
 
626
        @classmethod
 
627
        def from_param(cls, obj):
 
628
            return obj._as_parameter_
 
629
 
587
630
    # Classes
588
 
    class Credentials:
 
631
    class Credentials(With_from_param):
589
632
        def __init__(self):
590
 
            self._c_object = gnutls.certificate_credentials_t()
591
 
            gnutls.certificate_allocate_credentials(
592
 
                ctypes.byref(self._c_object))
 
633
            self._as_parameter_ = gnutls.certificate_credentials_t()
 
634
            gnutls.certificate_allocate_credentials(self)
593
635
            self.type = gnutls.CRD_CERTIFICATE
594
636
 
595
637
        def __del__(self):
596
 
            gnutls.certificate_free_credentials(self._c_object)
 
638
            gnutls.certificate_free_credentials(self)
597
639
 
598
 
    class ClientSession:
 
640
    class ClientSession(With_from_param):
599
641
        def __init__(self, socket, credentials=None):
600
 
            self._c_object = gnutls.session_t()
 
642
            self._as_parameter_ = gnutls.session_t()
601
643
            gnutls_flags = gnutls.CLIENT
602
644
            if gnutls.check_version(b"3.5.6"):
603
645
                gnutls_flags |= gnutls.NO_TICKETS
604
646
            if gnutls.has_rawpk:
605
647
                gnutls_flags |= gnutls.ENABLE_RAWPK
606
 
            gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
 
648
            gnutls.init(self, gnutls_flags)
607
649
            del gnutls_flags
608
 
            gnutls.set_default_priority(self._c_object)
609
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
610
 
            gnutls.handshake_set_private_extensions(self._c_object,
611
 
                                                    True)
 
650
            gnutls.set_default_priority(self)
 
651
            gnutls.transport_set_ptr(self, socket.fileno())
 
652
            gnutls.handshake_set_private_extensions(self, True)
612
653
            self.socket = socket
613
654
            if credentials is None:
614
655
                credentials = gnutls.Credentials()
615
 
            gnutls.credentials_set(self._c_object, credentials.type,
616
 
                                   ctypes.cast(credentials._c_object,
617
 
                                               ctypes.c_void_p))
 
656
            gnutls.credentials_set(self, credentials.type,
 
657
                                   credentials)
618
658
            self.credentials = credentials
619
659
 
620
660
        def __del__(self):
621
 
            gnutls.deinit(self._c_object)
 
661
            gnutls.deinit(self)
622
662
 
623
663
        def handshake(self):
624
 
            return gnutls.handshake(self._c_object)
 
664
            return gnutls.handshake(self)
625
665
 
626
666
        def send(self, data):
627
667
            data = bytes(data)
628
668
            data_len = len(data)
629
669
            while data_len > 0:
630
 
                data_len -= gnutls.record_send(self._c_object,
631
 
                                               data[-data_len:],
 
670
                data_len -= gnutls.record_send(self, data[-data_len:],
632
671
                                               data_len)
633
672
 
634
673
        def bye(self):
635
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
 
674
            return gnutls.bye(self, gnutls.SHUT_RDWR)
636
675
 
637
676
    # Error handling functions
638
677
    def _error_code(result):
639
678
        """A function to raise exceptions on errors, suitable
640
 
        for the 'restype' attribute on ctypes functions"""
641
 
        if result >= 0:
 
679
        for the "restype" attribute on ctypes functions"""
 
680
        if result >= gnutls.E_SUCCESS:
642
681
            return result
643
682
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
644
683
            raise gnutls.CertificateSecurityError(code=result)
645
684
        raise gnutls.Error(code=result)
646
685
 
647
 
    def _retry_on_error(result, func, arguments):
 
686
    def _retry_on_error(result, func, arguments,
 
687
                        _error_code=_error_code):
648
688
        """A function to retry on some errors, suitable
649
 
        for the 'errcheck' attribute on ctypes functions"""
650
 
        while result < 0:
 
689
        for the "errcheck" attribute on ctypes functions"""
 
690
        while result < gnutls.E_SUCCESS:
651
691
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
652
692
                return _error_code(result)
653
693
            result = func(*arguments)
658
698
 
659
699
    # Functions
660
700
    priority_set_direct = _library.gnutls_priority_set_direct
661
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
 
701
    priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
662
702
                                    ctypes.POINTER(ctypes.c_char_p)]
663
703
    priority_set_direct.restype = _error_code
664
704
 
665
705
    init = _library.gnutls_init
666
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
 
706
    init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
667
707
    init.restype = _error_code
668
708
 
669
709
    set_default_priority = _library.gnutls_set_default_priority
670
 
    set_default_priority.argtypes = [session_t]
 
710
    set_default_priority.argtypes = [ClientSession]
671
711
    set_default_priority.restype = _error_code
672
712
 
673
713
    record_send = _library.gnutls_record_send
674
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
 
714
    record_send.argtypes = [ClientSession, ctypes.c_void_p,
675
715
                            ctypes.c_size_t]
676
716
    record_send.restype = ctypes.c_ssize_t
677
717
    record_send.errcheck = _retry_on_error
679
719
    certificate_allocate_credentials = (
680
720
        _library.gnutls_certificate_allocate_credentials)
681
721
    certificate_allocate_credentials.argtypes = [
682
 
        ctypes.POINTER(certificate_credentials_t)]
 
722
        PointerTo(Credentials)]
683
723
    certificate_allocate_credentials.restype = _error_code
684
724
 
685
725
    certificate_free_credentials = (
686
726
        _library.gnutls_certificate_free_credentials)
687
 
    certificate_free_credentials.argtypes = [
688
 
        certificate_credentials_t]
 
727
    certificate_free_credentials.argtypes = [Credentials]
689
728
    certificate_free_credentials.restype = None
690
729
 
691
730
    handshake_set_private_extensions = (
692
731
        _library.gnutls_handshake_set_private_extensions)
693
 
    handshake_set_private_extensions.argtypes = [session_t,
 
732
    handshake_set_private_extensions.argtypes = [ClientSession,
694
733
                                                 ctypes.c_int]
695
734
    handshake_set_private_extensions.restype = None
696
735
 
697
736
    credentials_set = _library.gnutls_credentials_set
698
 
    credentials_set.argtypes = [session_t, credentials_type_t,
699
 
                                ctypes.c_void_p]
 
737
    credentials_set.argtypes = [ClientSession, credentials_type_t,
 
738
                                CastToVoidPointer(Credentials)]
700
739
    credentials_set.restype = _error_code
701
740
 
702
741
    strerror = _library.gnutls_strerror
704
743
    strerror.restype = ctypes.c_char_p
705
744
 
706
745
    certificate_type_get = _library.gnutls_certificate_type_get
707
 
    certificate_type_get.argtypes = [session_t]
 
746
    certificate_type_get.argtypes = [ClientSession]
708
747
    certificate_type_get.restype = _error_code
709
748
 
710
749
    certificate_get_peers = _library.gnutls_certificate_get_peers
711
 
    certificate_get_peers.argtypes = [session_t,
 
750
    certificate_get_peers.argtypes = [ClientSession,
712
751
                                      ctypes.POINTER(ctypes.c_uint)]
713
752
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
714
753
 
721
760
    global_set_log_function.restype = None
722
761
 
723
762
    deinit = _library.gnutls_deinit
724
 
    deinit.argtypes = [session_t]
 
763
    deinit.argtypes = [ClientSession]
725
764
    deinit.restype = None
726
765
 
727
766
    handshake = _library.gnutls_handshake
728
 
    handshake.argtypes = [session_t]
729
 
    handshake.restype = _error_code
 
767
    handshake.argtypes = [ClientSession]
 
768
    handshake.restype = ctypes.c_int
730
769
    handshake.errcheck = _retry_on_error
731
770
 
732
771
    transport_set_ptr = _library.gnutls_transport_set_ptr
733
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
 
772
    transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
734
773
    transport_set_ptr.restype = None
735
774
 
736
775
    bye = _library.gnutls_bye
737
 
    bye.argtypes = [session_t, close_request_t]
738
 
    bye.restype = _error_code
 
776
    bye.argtypes = [ClientSession, close_request_t]
 
777
    bye.restype = ctypes.c_int
739
778
    bye.errcheck = _retry_on_error
740
779
 
741
780
    check_version = _library.gnutls_check_version
758
797
 
759
798
        x509_crt_fmt_t = ctypes.c_int
760
799
 
761
 
        # All the function declarations below are from gnutls/abstract.h
 
800
        # All the function declarations below are from
 
801
        # gnutls/abstract.h
762
802
        pubkey_init = _library.gnutls_pubkey_init
763
803
        pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
764
804
        pubkey_init.restype = _error_code
778
818
        pubkey_deinit.argtypes = [pubkey_t]
779
819
        pubkey_deinit.restype = None
780
820
    else:
781
 
        # All the function declarations below are from gnutls/openpgp.h
 
821
        # All the function declarations below are from
 
822
        # gnutls/openpgp.h
782
823
 
783
824
        openpgp_crt_init = _library.gnutls_openpgp_crt_init
784
825
        openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
790
831
                                       openpgp_crt_fmt_t]
791
832
        openpgp_crt_import.restype = _error_code
792
833
 
793
 
        openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
794
 
        openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
795
 
                                            ctypes.POINTER(ctypes.c_uint)]
 
834
        openpgp_crt_verify_self = \
 
835
            _library.gnutls_openpgp_crt_verify_self
 
836
        openpgp_crt_verify_self.argtypes = [
 
837
            openpgp_crt_t,
 
838
            ctypes.c_uint,
 
839
            ctypes.POINTER(ctypes.c_uint),
 
840
        ]
796
841
        openpgp_crt_verify_self.restype = _error_code
797
842
 
798
843
        openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
809
854
 
810
855
    if check_version(b"3.6.4"):
811
856
        certificate_type_get2 = _library.gnutls_certificate_type_get2
812
 
        certificate_type_get2.argtypes = [session_t, ctypes.c_int]
 
857
        certificate_type_get2.argtypes = [ClientSession, ctypes.c_int]
813
858
        certificate_type_get2.restype = _error_code
814
859
 
815
860
    # Remove non-public functions
831
876
    """A representation of a client host served by this server.
832
877
 
833
878
    Attributes:
834
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
879
    approved:   bool(); None if not yet approved/disapproved
835
880
    approval_delay: datetime.timedelta(); Time to wait for approval
836
881
    approval_duration: datetime.timedelta(); Duration of one approval
837
882
    checker: multiprocessing.Process(); a running checker process used
838
 
             to see if the client lives. 'None' if no process is
 
883
             to see if the client lives. None if no process is
839
884
             running.
840
885
    checker_callback_tag: a GLib event source tag, or None
841
886
    checker_command: string; External command which is run to check
1118
1163
        if self.checker is None:
1119
1164
            # Escape attributes for the shell
1120
1165
            escaped_attrs = {
1121
 
                attr: re.escape(str(getattr(self, attr)))
 
1166
                attr: shlex.quote(str(getattr(self, attr)))
1122
1167
                for attr in self.runtime_expansions}
1123
1168
            try:
1124
1169
                command = self.checker_command % escaped_attrs
1197
1242
        func._dbus_name = func.__name__
1198
1243
        if func._dbus_name.endswith("_dbus_property"):
1199
1244
            func._dbus_name = func._dbus_name[:-14]
1200
 
        func._dbus_get_args_options = {'byte_arrays': byte_arrays}
 
1245
        func._dbus_get_args_options = {"byte_arrays": byte_arrays}
1201
1246
        return func
1202
1247
 
1203
1248
    return decorator
1292
1337
 
1293
1338
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1294
1339
                         out_signature="s",
1295
 
                         path_keyword='object_path',
1296
 
                         connection_keyword='connection')
 
1340
                         path_keyword="object_path",
 
1341
                         connection_keyword="connection")
1297
1342
    def Introspect(self, object_path, connection):
1298
1343
        """Overloading of standard D-Bus method.
1299
1344
 
1452
1497
 
1453
1498
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1454
1499
                         out_signature="s",
1455
 
                         path_keyword='object_path',
1456
 
                         connection_keyword='connection')
 
1500
                         path_keyword="object_path",
 
1501
                         connection_keyword="connection")
1457
1502
    def Introspect(self, object_path, connection):
1458
1503
        """Overloading of standard D-Bus method.
1459
1504
 
1554
1599
 
1555
1600
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1556
1601
                         out_signature="s",
1557
 
                         path_keyword='object_path',
1558
 
                         connection_keyword='connection')
 
1602
                         path_keyword="object_path",
 
1603
                         connection_keyword="connection")
1559
1604
    def Introspect(self, object_path, connection):
1560
1605
        """Overloading of standard D-Bus method.
1561
1606
 
2227
2272
class ProxyClient:
2228
2273
    def __init__(self, child_pipe, key_id, fpr, address):
2229
2274
        self._pipe = child_pipe
2230
 
        self._pipe.send(('init', key_id, fpr, address))
 
2275
        self._pipe.send(("init", key_id, fpr, address))
2231
2276
        if not self._pipe.recv():
2232
2277
            raise KeyError(key_id or fpr)
2233
2278
 
2234
2279
    def __getattribute__(self, name):
2235
 
        if name == '_pipe':
 
2280
        if name == "_pipe":
2236
2281
            return super(ProxyClient, self).__getattribute__(name)
2237
 
        self._pipe.send(('getattr', name))
 
2282
        self._pipe.send(("getattr", name))
2238
2283
        data = self._pipe.recv()
2239
 
        if data[0] == 'data':
 
2284
        if data[0] == "data":
2240
2285
            return data[1]
2241
 
        if data[0] == 'function':
 
2286
        if data[0] == "function":
2242
2287
 
2243
2288
            def func(*args, **kwargs):
2244
 
                self._pipe.send(('funcall', name, args, kwargs))
 
2289
                self._pipe.send(("funcall", name, args, kwargs))
2245
2290
                return self._pipe.recv()[1]
2246
2291
 
2247
2292
            return func
2248
2293
 
2249
2294
    def __setattr__(self, name, value):
2250
 
        if name == '_pipe':
 
2295
        if name == "_pipe":
2251
2296
            return super(ProxyClient, self).__setattr__(name, value)
2252
 
        self._pipe.send(('setattr', name, value))
 
2297
        self._pipe.send(("setattr", name, value))
2253
2298
 
2254
2299
 
2255
2300
class ClientHandler(socketserver.BaseRequestHandler, object):
2267
2312
 
2268
2313
            session = gnutls.ClientSession(self.request)
2269
2314
 
2270
 
            # priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
2315
            # priority = ":".join(("NONE", "+VERS-TLS1.1",
2271
2316
            #                       "+AES-256-CBC", "+SHA1",
2272
2317
            #                       "+COMP-NULL", "+CTYPE-OPENPGP",
2273
2318
            #                       "+DHE-DSS"))
2275
2320
            priority = self.server.gnutls_priority
2276
2321
            if priority is None:
2277
2322
                priority = "NORMAL"
2278
 
            gnutls.priority_set_direct(session._c_object,
2279
 
                                       priority.encode("utf-8"),
2280
 
                                       None)
 
2323
            gnutls.priority_set_direct(session,
 
2324
                                       priority.encode("utf-8"), None)
2281
2325
 
2282
2326
            # Start communication using the Mandos protocol
2283
2327
            # Get protocol number
2310
2354
                    except (TypeError, gnutls.Error) as error:
2311
2355
                        logger.warning("Bad certificate: %s", error)
2312
2356
                        return
2313
 
                    logger.debug("Key ID: %s", key_id)
 
2357
                    logger.debug("Key ID: %s",
 
2358
                                 key_id.decode("utf-8",
 
2359
                                               errors="replace"))
2314
2360
 
2315
2361
                else:
2316
2362
                    key_id = b""
2408
2454
    def peer_certificate(session):
2409
2455
        "Return the peer's certificate as a bytestring"
2410
2456
        try:
2411
 
            cert_type = gnutls.certificate_type_get2(session._c_object,
2412
 
                                                     gnutls.CTYPE_PEERS)
 
2457
            cert_type = gnutls.certificate_type_get2(
 
2458
                session, gnutls.CTYPE_PEERS)
2413
2459
        except AttributeError:
2414
 
            cert_type = gnutls.certificate_type_get(session._c_object)
 
2460
            cert_type = gnutls.certificate_type_get(session)
2415
2461
        if gnutls.has_rawpk:
2416
2462
            valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2417
2463
        else:
2424
2470
            return b""
2425
2471
        list_size = ctypes.c_uint(1)
2426
2472
        cert_list = (gnutls.certificate_get_peers
2427
 
                     (session._c_object, ctypes.byref(list_size)))
 
2473
                     (session, ctypes.byref(list_size)))
2428
2474
        if not bool(cert_list) and list_size.value != 0:
2429
2475
            raise gnutls.Error("error getting peer certificate")
2430
2476
        if list_size.value == 0:
2452
2498
        buf = ctypes.create_string_buffer(32)
2453
2499
        buf_len = ctypes.c_size_t(len(buf))
2454
2500
        # Get the key ID from the raw public key into the buffer
2455
 
        gnutls.pubkey_get_key_id(pubkey,
2456
 
                                 gnutls.KEYID_USE_SHA256,
2457
 
                                 ctypes.cast(ctypes.byref(buf),
2458
 
                                             ctypes.POINTER(ctypes.c_ubyte)),
2459
 
                                 ctypes.byref(buf_len))
 
2501
        gnutls.pubkey_get_key_id(
 
2502
            pubkey,
 
2503
            gnutls.KEYID_USE_SHA256,
 
2504
            ctypes.cast(ctypes.byref(buf),
 
2505
                        ctypes.POINTER(ctypes.c_ubyte)),
 
2506
            ctypes.byref(buf_len))
2460
2507
        # Deinit the certificate
2461
2508
        gnutls.pubkey_deinit(pubkey)
2462
2509
 
2543
2590
 
2544
2591
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2545
2592
                     socketserver.TCPServer):
2546
 
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
 
2593
    """IPv6-capable TCP server.  Accepts None as address and/or port
2547
2594
 
2548
2595
    Attributes:
2549
2596
        enabled:        Boolean; whether this server is activated yet
2701
2748
        request = parent_pipe.recv()
2702
2749
        command = request[0]
2703
2750
 
2704
 
        if command == 'init':
 
2751
        if command == "init":
2705
2752
            key_id = request[1].decode("ascii")
2706
2753
            fpr = request[2].decode("ascii")
2707
2754
            address = request[3]
2708
2755
 
2709
2756
            for c in self.clients.values():
2710
 
                if key_id == "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855":
 
2757
                if key_id == ("E3B0C44298FC1C149AFBF4C8996FB924"
 
2758
                              "27AE41E4649B934CA495991B7852B855"):
2711
2759
                    continue
2712
2760
                if key_id and c.key_id == key_id:
2713
2761
                    client = c
2736
2784
            # remove the old hook in favor of the new above hook on
2737
2785
            # same fileno
2738
2786
            return False
2739
 
        if command == 'funcall':
 
2787
        if command == "funcall":
2740
2788
            funcname = request[1]
2741
2789
            args = request[2]
2742
2790
            kwargs = request[3]
2743
2791
 
2744
 
            parent_pipe.send(('data', getattr(client_object,
 
2792
            parent_pipe.send(("data", getattr(client_object,
2745
2793
                                              funcname)(*args,
2746
2794
                                                        **kwargs)))
2747
2795
 
2748
 
        if command == 'getattr':
 
2796
        if command == "getattr":
2749
2797
            attrname = request[1]
2750
2798
            if isinstance(client_object.__getattribute__(attrname),
2751
 
                          collections.Callable):
2752
 
                parent_pipe.send(('function', ))
 
2799
                          collections.abc.Callable):
 
2800
                parent_pipe.send(("function", ))
2753
2801
            else:
2754
2802
                parent_pipe.send((
2755
 
                    'data', client_object.__getattribute__(attrname)))
 
2803
                    "data", client_object.__getattribute__(attrname)))
2756
2804
 
2757
 
        if command == 'setattr':
 
2805
        if command == "setattr":
2758
2806
            attrname = request[1]
2759
2807
            value = request[2]
2760
2808
            setattr(client_object, attrname, value)
2765
2813
def rfc3339_duration_to_delta(duration):
2766
2814
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2767
2815
 
2768
 
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
2769
 
    True
2770
 
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
2771
 
    True
2772
 
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(0, 3600)
2773
 
    True
2774
 
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
2775
 
    True
2776
 
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
2777
 
    True
2778
 
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
2779
 
    True
2780
 
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
2781
 
    True
 
2816
    >>> timedelta = datetime.timedelta
 
2817
    >>> rfc3339_duration_to_delta("P7D") == timedelta(7)
 
2818
    True
 
2819
    >>> rfc3339_duration_to_delta("PT60S") == timedelta(0, 60)
 
2820
    True
 
2821
    >>> rfc3339_duration_to_delta("PT60M") == timedelta(0, 3600)
 
2822
    True
 
2823
    >>> rfc3339_duration_to_delta("PT24H") == timedelta(1)
 
2824
    True
 
2825
    >>> rfc3339_duration_to_delta("P1W") == timedelta(7)
 
2826
    True
 
2827
    >>> rfc3339_duration_to_delta("PT5M30S") == timedelta(0, 330)
 
2828
    True
 
2829
    >>> rfc3339_duration_to_delta("P1DT3M20S") == timedelta(1, 200)
 
2830
    True
 
2831
    >>> del timedelta
2782
2832
    """
2783
2833
 
2784
2834
    # Parsing an RFC 3339 duration with regular expressions is not
2864
2914
def string_to_delta(interval):
2865
2915
    """Parse a string and return a datetime.timedelta
2866
2916
 
2867
 
    >>> string_to_delta('7d') == datetime.timedelta(7)
2868
 
    True
2869
 
    >>> string_to_delta('60s') == datetime.timedelta(0, 60)
2870
 
    True
2871
 
    >>> string_to_delta('60m') == datetime.timedelta(0, 3600)
2872
 
    True
2873
 
    >>> string_to_delta('24h') == datetime.timedelta(1)
2874
 
    True
2875
 
    >>> string_to_delta('1w') == datetime.timedelta(7)
2876
 
    True
2877
 
    >>> string_to_delta('5m 30s') == datetime.timedelta(0, 330)
 
2917
    >>> string_to_delta("7d") == datetime.timedelta(7)
 
2918
    True
 
2919
    >>> string_to_delta("60s") == datetime.timedelta(0, 60)
 
2920
    True
 
2921
    >>> string_to_delta("60m") == datetime.timedelta(0, 3600)
 
2922
    True
 
2923
    >>> string_to_delta("24h") == datetime.timedelta(1)
 
2924
    True
 
2925
    >>> string_to_delta("1w") == datetime.timedelta(7)
 
2926
    True
 
2927
    >>> string_to_delta("5m 30s") == datetime.timedelta(0, 330)
2878
2928
    True
2879
2929
    """
2880
2930
 
3084
3134
 
3085
3135
    if server_settings["servicename"] != "Mandos":
3086
3136
        syslogger.setFormatter(
3087
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
3088
 
                              ' %(levelname)s: %(message)s'.format(
 
3137
            logging.Formatter("Mandos ({}) [%(process)d]:"
 
3138
                              " %(levelname)s: %(message)s".format(
3089
3139
                                  server_settings["servicename"])))
3090
3140
 
3091
3141
    # Parse config file with clients
3151
3201
 
3152
3202
        @gnutls.log_func
3153
3203
        def debug_gnutls(level, string):
3154
 
            logger.debug("GnuTLS: %s", string[:-1])
 
3204
            logger.debug("GnuTLS: %s",
 
3205
                         string[:-1].decode("utf-8",
 
3206
                                            errors="replace"))
3155
3207
 
3156
3208
        gnutls.global_set_log_function(debug_gnutls)
3157
3209
 
3532
3584
 
3533
3585
        try:
3534
3586
            with tempfile.NamedTemporaryFile(
3535
 
                    mode='wb',
 
3587
                    mode="wb",
3536
3588
                    suffix=".pickle",
3537
 
                    prefix='clients-',
 
3589
                    prefix="clients-",
3538
3590
                    dir=os.path.dirname(stored_state_path),
3539
3591
                    delete=False) as stored_state:
3540
3592
                pickle.dump((clients, client_settings), stored_state,
3627
3679
 
3628
3680
def should_only_run_tests():
3629
3681
    parser = argparse.ArgumentParser(add_help=False)
3630
 
    parser.add_argument("--check", action='store_true')
 
3682
    parser.add_argument("--check", action="store_true")
3631
3683
    args, unknown_args = parser.parse_known_args()
3632
3684
    run_tests = args.check
3633
3685
    if run_tests:
3641
3693
    tests.addTests(doctest.DocTestSuite())
3642
3694
    return tests
3643
3695
 
3644
 
if __name__ == '__main__':
 
3696
if __name__ == "__main__":
3645
3697
    try:
3646
3698
        if should_only_run_tests():
3647
3699
            # Call using ./mandos --check [--verbose]