/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 at recompile
  • Date: 2019-12-04 23:52:20 UTC
  • Revision ID: teddy@recompile.se-20191204235220-yn88brp0scmqwy2t
Remove non-project-specific pattern from .bzrignore

Only project-specific patterns should be in the .bzrignore file.
Other generic patterns should be in the ~/.config/breezy/ignore and
~/.bazaar/ignore files.

* .bzrignore (.tramp_history): Remove.

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