/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:25:49 UTC
  • Revision ID: teddy@recompile.se-20220423232549-1uul4i3jwhums0ek
Minor text adjustment in mandos(8) manual page

* mandos.xml (DESCRIPTION): Break long line.
  (SEE ALSO/RFC 4291): Fix grammatical mistake.

Show diffs side-by-side

added added

removed removed

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