/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:
189
189
        facility=logging.handlers.SysLogHandler.LOG_DAEMON,
190
190
        address="/dev/log"))
191
191
    syslogger.setFormatter(logging.Formatter
192
 
                           ('Mandos [%(process)d]: %(levelname)s:'
193
 
                            ' %(message)s'))
 
192
                           ("Mandos [%(process)d]: %(levelname)s:"
 
193
                            " %(message)s"))
194
194
    logger.addHandler(syslogger)
195
195
 
196
196
    if debug:
197
197
        console = logging.StreamHandler()
198
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
199
 
                                               ' [%(process)d]:'
200
 
                                               ' %(levelname)s:'
201
 
                                               ' %(message)s'))
 
198
        console.setFormatter(logging.Formatter("%(asctime)s %(name)s"
 
199
                                               " [%(process)d]:"
 
200
                                               " %(levelname)s:"
 
201
                                               " %(message)s"))
202
202
        logger.addHandler(console)
203
203
    logger.setLevel(level)
204
204
 
224
224
        except OSError as e:
225
225
            if e.errno != errno.ENOENT:
226
226
                raise
227
 
        self.gnupgargs = ['--batch',
228
 
                          '--homedir', self.tempdir,
229
 
                          '--force-mdc',
230
 
                          '--quiet']
 
227
        self.gnupgargs = ["--batch",
 
228
                          "--homedir", self.tempdir,
 
229
                          "--force-mdc",
 
230
                          "--quiet"]
231
231
        # Only GPG version 1 has the --no-use-agent option.
232
232
        if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
233
233
            self.gnupgargs.append("--no-use-agent")
272
272
                dir=self.tempdir) as passfile:
273
273
            passfile.write(passphrase)
274
274
            passfile.flush()
275
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
276
 
                                     '--passphrase-file',
 
275
            proc = subprocess.Popen([self.gpg, "--symmetric",
 
276
                                     "--passphrase-file",
277
277
                                     passfile.name]
278
278
                                    + self.gnupgargs,
279
279
                                    stdin=subprocess.PIPE,
290
290
                dir=self.tempdir) as passfile:
291
291
            passfile.write(passphrase)
292
292
            passfile.flush()
293
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
294
 
                                     '--passphrase-file',
 
293
            proc = subprocess.Popen([self.gpg, "--decrypt",
 
294
                                     "--passphrase-file",
295
295
                                     passfile.name]
296
296
                                    + self.gnupgargs,
297
297
                                    stdin=subprocess.PIPE,
350
350
    Attributes:
351
351
    interface: integer; avahi.IF_UNSPEC or an interface index.
352
352
               Used to optionally bind to the specified interface.
353
 
    name: string; Example: 'Mandos'
354
 
    type: string; Example: '_mandos._tcp'.
 
353
    name: string; Example: "Mandos"
 
354
    type: string; Example: "_mandos._tcp".
355
355
     See <https://www.iana.org/assignments/service-names-port-numbers>
356
356
    port: integer; what port to announce
357
357
    TXT: list of strings; TXT record for the service
435
435
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
436
436
        self.entry_group_state_changed_match = (
437
437
            self.group.connect_to_signal(
438
 
                'StateChanged', self.entry_group_state_changed))
 
438
                "StateChanged", self.entry_group_state_changed))
439
439
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
440
440
                     self.name, self.type)
441
441
        self.group.AddService(
527
527
        ret = super(AvahiServiceToSyslog, self).rename(*args,
528
528
                                                       **kwargs)
529
529
        syslogger.setFormatter(logging.Formatter(
530
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
 
530
            "Mandos ({}) [%(process)d]: %(levelname)s: %(message)s"
531
531
            .format(self.name)))
532
532
        return ret
533
533
 
563
563
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
564
564
 
565
565
    # Types
566
 
    class session_int(ctypes.Structure):
 
566
    class _session_int(ctypes.Structure):
567
567
        _fields_ = []
568
 
    session_t = ctypes.POINTER(session_int)
 
568
    session_t = ctypes.POINTER(_session_int)
569
569
 
570
570
    class certificate_credentials_st(ctypes.Structure):
571
571
        _fields_ = []
574
574
    certificate_type_t = ctypes.c_int
575
575
 
576
576
    class datum_t(ctypes.Structure):
577
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
578
 
                    ('size', ctypes.c_uint)]
 
577
        _fields_ = [("data", ctypes.POINTER(ctypes.c_ubyte)),
 
578
                    ("size", ctypes.c_uint)]
579
579
 
580
 
    class openpgp_crt_int(ctypes.Structure):
 
580
    class _openpgp_crt_int(ctypes.Structure):
581
581
        _fields_ = []
582
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
 
582
    openpgp_crt_t = ctypes.POINTER(_openpgp_crt_int)
583
583
    openpgp_crt_fmt_t = ctypes.c_int  # gnutls/openpgp.h
584
584
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
585
585
    credentials_type_t = ctypes.c_int
594
594
            # gnutls.strerror()
595
595
            self.code = code
596
596
            if message is None and code is not None:
597
 
                message = gnutls.strerror(code)
 
597
                message = gnutls.strerror(code).decode(
 
598
                    "utf-8", errors="replace")
598
599
            return super(gnutls.Error, self).__init__(
599
600
                message, *args)
600
601
 
601
602
    class CertificateSecurityError(Error):
602
603
        pass
603
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
 
604
630
    # Classes
605
 
    class Credentials:
 
631
    class Credentials(With_from_param):
606
632
        def __init__(self):
607
 
            self._c_object = gnutls.certificate_credentials_t()
608
 
            gnutls.certificate_allocate_credentials(
609
 
                ctypes.byref(self._c_object))
 
633
            self._as_parameter_ = gnutls.certificate_credentials_t()
 
634
            gnutls.certificate_allocate_credentials(self)
610
635
            self.type = gnutls.CRD_CERTIFICATE
611
636
 
612
637
        def __del__(self):
613
 
            gnutls.certificate_free_credentials(self._c_object)
 
638
            gnutls.certificate_free_credentials(self)
614
639
 
615
 
    class ClientSession:
 
640
    class ClientSession(With_from_param):
616
641
        def __init__(self, socket, credentials=None):
617
 
            self._c_object = gnutls.session_t()
 
642
            self._as_parameter_ = gnutls.session_t()
618
643
            gnutls_flags = gnutls.CLIENT
619
644
            if gnutls.check_version(b"3.5.6"):
620
645
                gnutls_flags |= gnutls.NO_TICKETS
621
646
            if gnutls.has_rawpk:
622
647
                gnutls_flags |= gnutls.ENABLE_RAWPK
623
 
            gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
 
648
            gnutls.init(self, gnutls_flags)
624
649
            del gnutls_flags
625
 
            gnutls.set_default_priority(self._c_object)
626
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
627
 
            gnutls.handshake_set_private_extensions(self._c_object,
628
 
                                                    True)
 
650
            gnutls.set_default_priority(self)
 
651
            gnutls.transport_set_ptr(self, socket.fileno())
 
652
            gnutls.handshake_set_private_extensions(self, True)
629
653
            self.socket = socket
630
654
            if credentials is None:
631
655
                credentials = gnutls.Credentials()
632
 
            gnutls.credentials_set(self._c_object, credentials.type,
633
 
                                   ctypes.cast(credentials._c_object,
634
 
                                               ctypes.c_void_p))
 
656
            gnutls.credentials_set(self, credentials.type,
 
657
                                   credentials)
635
658
            self.credentials = credentials
636
659
 
637
660
        def __del__(self):
638
 
            gnutls.deinit(self._c_object)
 
661
            gnutls.deinit(self)
639
662
 
640
663
        def handshake(self):
641
 
            return gnutls.handshake(self._c_object)
 
664
            return gnutls.handshake(self)
642
665
 
643
666
        def send(self, data):
644
667
            data = bytes(data)
645
668
            data_len = len(data)
646
669
            while data_len > 0:
647
 
                data_len -= gnutls.record_send(self._c_object,
648
 
                                               data[-data_len:],
 
670
                data_len -= gnutls.record_send(self, data[-data_len:],
649
671
                                               data_len)
650
672
 
651
673
        def bye(self):
652
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
 
674
            return gnutls.bye(self, gnutls.SHUT_RDWR)
653
675
 
654
676
    # Error handling functions
655
677
    def _error_code(result):
656
678
        """A function to raise exceptions on errors, suitable
657
 
        for the 'restype' attribute on ctypes functions"""
658
 
        if result >= 0:
 
679
        for the "restype" attribute on ctypes functions"""
 
680
        if result >= gnutls.E_SUCCESS:
659
681
            return result
660
682
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
661
683
            raise gnutls.CertificateSecurityError(code=result)
664
686
    def _retry_on_error(result, func, arguments,
665
687
                        _error_code=_error_code):
666
688
        """A function to retry on some errors, suitable
667
 
        for the 'errcheck' attribute on ctypes functions"""
668
 
        while result < 0:
 
689
        for the "errcheck" attribute on ctypes functions"""
 
690
        while result < gnutls.E_SUCCESS:
669
691
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
670
692
                return _error_code(result)
671
693
            result = func(*arguments)
676
698
 
677
699
    # Functions
678
700
    priority_set_direct = _library.gnutls_priority_set_direct
679
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
 
701
    priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
680
702
                                    ctypes.POINTER(ctypes.c_char_p)]
681
703
    priority_set_direct.restype = _error_code
682
704
 
683
705
    init = _library.gnutls_init
684
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
 
706
    init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
685
707
    init.restype = _error_code
686
708
 
687
709
    set_default_priority = _library.gnutls_set_default_priority
688
 
    set_default_priority.argtypes = [session_t]
 
710
    set_default_priority.argtypes = [ClientSession]
689
711
    set_default_priority.restype = _error_code
690
712
 
691
713
    record_send = _library.gnutls_record_send
692
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
 
714
    record_send.argtypes = [ClientSession, ctypes.c_void_p,
693
715
                            ctypes.c_size_t]
694
716
    record_send.restype = ctypes.c_ssize_t
695
717
    record_send.errcheck = _retry_on_error
697
719
    certificate_allocate_credentials = (
698
720
        _library.gnutls_certificate_allocate_credentials)
699
721
    certificate_allocate_credentials.argtypes = [
700
 
        ctypes.POINTER(certificate_credentials_t)]
 
722
        PointerTo(Credentials)]
701
723
    certificate_allocate_credentials.restype = _error_code
702
724
 
703
725
    certificate_free_credentials = (
704
726
        _library.gnutls_certificate_free_credentials)
705
 
    certificate_free_credentials.argtypes = [
706
 
        certificate_credentials_t]
 
727
    certificate_free_credentials.argtypes = [Credentials]
707
728
    certificate_free_credentials.restype = None
708
729
 
709
730
    handshake_set_private_extensions = (
710
731
        _library.gnutls_handshake_set_private_extensions)
711
 
    handshake_set_private_extensions.argtypes = [session_t,
 
732
    handshake_set_private_extensions.argtypes = [ClientSession,
712
733
                                                 ctypes.c_int]
713
734
    handshake_set_private_extensions.restype = None
714
735
 
715
736
    credentials_set = _library.gnutls_credentials_set
716
 
    credentials_set.argtypes = [session_t, credentials_type_t,
717
 
                                ctypes.c_void_p]
 
737
    credentials_set.argtypes = [ClientSession, credentials_type_t,
 
738
                                CastToVoidPointer(Credentials)]
718
739
    credentials_set.restype = _error_code
719
740
 
720
741
    strerror = _library.gnutls_strerror
722
743
    strerror.restype = ctypes.c_char_p
723
744
 
724
745
    certificate_type_get = _library.gnutls_certificate_type_get
725
 
    certificate_type_get.argtypes = [session_t]
 
746
    certificate_type_get.argtypes = [ClientSession]
726
747
    certificate_type_get.restype = _error_code
727
748
 
728
749
    certificate_get_peers = _library.gnutls_certificate_get_peers
729
 
    certificate_get_peers.argtypes = [session_t,
 
750
    certificate_get_peers.argtypes = [ClientSession,
730
751
                                      ctypes.POINTER(ctypes.c_uint)]
731
752
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
732
753
 
739
760
    global_set_log_function.restype = None
740
761
 
741
762
    deinit = _library.gnutls_deinit
742
 
    deinit.argtypes = [session_t]
 
763
    deinit.argtypes = [ClientSession]
743
764
    deinit.restype = None
744
765
 
745
766
    handshake = _library.gnutls_handshake
746
 
    handshake.argtypes = [session_t]
747
 
    handshake.restype = _error_code
 
767
    handshake.argtypes = [ClientSession]
 
768
    handshake.restype = ctypes.c_int
748
769
    handshake.errcheck = _retry_on_error
749
770
 
750
771
    transport_set_ptr = _library.gnutls_transport_set_ptr
751
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
 
772
    transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
752
773
    transport_set_ptr.restype = None
753
774
 
754
775
    bye = _library.gnutls_bye
755
 
    bye.argtypes = [session_t, close_request_t]
756
 
    bye.restype = _error_code
 
776
    bye.argtypes = [ClientSession, close_request_t]
 
777
    bye.restype = ctypes.c_int
757
778
    bye.errcheck = _retry_on_error
758
779
 
759
780
    check_version = _library.gnutls_check_version
833
854
 
834
855
    if check_version(b"3.6.4"):
835
856
        certificate_type_get2 = _library.gnutls_certificate_type_get2
836
 
        certificate_type_get2.argtypes = [session_t, ctypes.c_int]
 
857
        certificate_type_get2.argtypes = [ClientSession, ctypes.c_int]
837
858
        certificate_type_get2.restype = _error_code
838
859
 
839
860
    # Remove non-public functions
855
876
    """A representation of a client host served by this server.
856
877
 
857
878
    Attributes:
858
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
879
    approved:   bool(); None if not yet approved/disapproved
859
880
    approval_delay: datetime.timedelta(); Time to wait for approval
860
881
    approval_duration: datetime.timedelta(); Duration of one approval
861
882
    checker: multiprocessing.Process(); a running checker process used
862
 
             to see if the client lives. 'None' if no process is
 
883
             to see if the client lives. None if no process is
863
884
             running.
864
885
    checker_callback_tag: a GLib event source tag, or None
865
886
    checker_command: string; External command which is run to check
1221
1242
        func._dbus_name = func.__name__
1222
1243
        if func._dbus_name.endswith("_dbus_property"):
1223
1244
            func._dbus_name = func._dbus_name[:-14]
1224
 
        func._dbus_get_args_options = {'byte_arrays': byte_arrays}
 
1245
        func._dbus_get_args_options = {"byte_arrays": byte_arrays}
1225
1246
        return func
1226
1247
 
1227
1248
    return decorator
1316
1337
 
1317
1338
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1318
1339
                         out_signature="s",
1319
 
                         path_keyword='object_path',
1320
 
                         connection_keyword='connection')
 
1340
                         path_keyword="object_path",
 
1341
                         connection_keyword="connection")
1321
1342
    def Introspect(self, object_path, connection):
1322
1343
        """Overloading of standard D-Bus method.
1323
1344
 
1476
1497
 
1477
1498
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1478
1499
                         out_signature="s",
1479
 
                         path_keyword='object_path',
1480
 
                         connection_keyword='connection')
 
1500
                         path_keyword="object_path",
 
1501
                         connection_keyword="connection")
1481
1502
    def Introspect(self, object_path, connection):
1482
1503
        """Overloading of standard D-Bus method.
1483
1504
 
1578
1599
 
1579
1600
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1580
1601
                         out_signature="s",
1581
 
                         path_keyword='object_path',
1582
 
                         connection_keyword='connection')
 
1602
                         path_keyword="object_path",
 
1603
                         connection_keyword="connection")
1583
1604
    def Introspect(self, object_path, connection):
1584
1605
        """Overloading of standard D-Bus method.
1585
1606
 
2251
2272
class ProxyClient:
2252
2273
    def __init__(self, child_pipe, key_id, fpr, address):
2253
2274
        self._pipe = child_pipe
2254
 
        self._pipe.send(('init', key_id, fpr, address))
 
2275
        self._pipe.send(("init", key_id, fpr, address))
2255
2276
        if not self._pipe.recv():
2256
2277
            raise KeyError(key_id or fpr)
2257
2278
 
2258
2279
    def __getattribute__(self, name):
2259
 
        if name == '_pipe':
 
2280
        if name == "_pipe":
2260
2281
            return super(ProxyClient, self).__getattribute__(name)
2261
 
        self._pipe.send(('getattr', name))
 
2282
        self._pipe.send(("getattr", name))
2262
2283
        data = self._pipe.recv()
2263
 
        if data[0] == 'data':
 
2284
        if data[0] == "data":
2264
2285
            return data[1]
2265
 
        if data[0] == 'function':
 
2286
        if data[0] == "function":
2266
2287
 
2267
2288
            def func(*args, **kwargs):
2268
 
                self._pipe.send(('funcall', name, args, kwargs))
 
2289
                self._pipe.send(("funcall", name, args, kwargs))
2269
2290
                return self._pipe.recv()[1]
2270
2291
 
2271
2292
            return func
2272
2293
 
2273
2294
    def __setattr__(self, name, value):
2274
 
        if name == '_pipe':
 
2295
        if name == "_pipe":
2275
2296
            return super(ProxyClient, self).__setattr__(name, value)
2276
 
        self._pipe.send(('setattr', name, value))
 
2297
        self._pipe.send(("setattr", name, value))
2277
2298
 
2278
2299
 
2279
2300
class ClientHandler(socketserver.BaseRequestHandler, object):
2291
2312
 
2292
2313
            session = gnutls.ClientSession(self.request)
2293
2314
 
2294
 
            # priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
2315
            # priority = ":".join(("NONE", "+VERS-TLS1.1",
2295
2316
            #                       "+AES-256-CBC", "+SHA1",
2296
2317
            #                       "+COMP-NULL", "+CTYPE-OPENPGP",
2297
2318
            #                       "+DHE-DSS"))
2299
2320
            priority = self.server.gnutls_priority
2300
2321
            if priority is None:
2301
2322
                priority = "NORMAL"
2302
 
            gnutls.priority_set_direct(session._c_object,
2303
 
                                       priority.encode("utf-8"),
2304
 
                                       None)
 
2323
            gnutls.priority_set_direct(session,
 
2324
                                       priority.encode("utf-8"), None)
2305
2325
 
2306
2326
            # Start communication using the Mandos protocol
2307
2327
            # Get protocol number
2334
2354
                    except (TypeError, gnutls.Error) as error:
2335
2355
                        logger.warning("Bad certificate: %s", error)
2336
2356
                        return
2337
 
                    logger.debug("Key ID: %s", key_id)
 
2357
                    logger.debug("Key ID: %s",
 
2358
                                 key_id.decode("utf-8",
 
2359
                                               errors="replace"))
2338
2360
 
2339
2361
                else:
2340
2362
                    key_id = b""
2432
2454
    def peer_certificate(session):
2433
2455
        "Return the peer's certificate as a bytestring"
2434
2456
        try:
2435
 
            cert_type = gnutls.certificate_type_get2(session._c_object,
2436
 
                                                     gnutls.CTYPE_PEERS)
 
2457
            cert_type = gnutls.certificate_type_get2(
 
2458
                session, gnutls.CTYPE_PEERS)
2437
2459
        except AttributeError:
2438
 
            cert_type = gnutls.certificate_type_get(session._c_object)
 
2460
            cert_type = gnutls.certificate_type_get(session)
2439
2461
        if gnutls.has_rawpk:
2440
2462
            valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2441
2463
        else:
2448
2470
            return b""
2449
2471
        list_size = ctypes.c_uint(1)
2450
2472
        cert_list = (gnutls.certificate_get_peers
2451
 
                     (session._c_object, ctypes.byref(list_size)))
 
2473
                     (session, ctypes.byref(list_size)))
2452
2474
        if not bool(cert_list) and list_size.value != 0:
2453
2475
            raise gnutls.Error("error getting peer certificate")
2454
2476
        if list_size.value == 0:
2568
2590
 
2569
2591
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2570
2592
                     socketserver.TCPServer):
2571
 
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
 
2593
    """IPv6-capable TCP server.  Accepts None as address and/or port
2572
2594
 
2573
2595
    Attributes:
2574
2596
        enabled:        Boolean; whether this server is activated yet
2726
2748
        request = parent_pipe.recv()
2727
2749
        command = request[0]
2728
2750
 
2729
 
        if command == 'init':
 
2751
        if command == "init":
2730
2752
            key_id = request[1].decode("ascii")
2731
2753
            fpr = request[2].decode("ascii")
2732
2754
            address = request[3]
2762
2784
            # remove the old hook in favor of the new above hook on
2763
2785
            # same fileno
2764
2786
            return False
2765
 
        if command == 'funcall':
 
2787
        if command == "funcall":
2766
2788
            funcname = request[1]
2767
2789
            args = request[2]
2768
2790
            kwargs = request[3]
2769
2791
 
2770
 
            parent_pipe.send(('data', getattr(client_object,
 
2792
            parent_pipe.send(("data", getattr(client_object,
2771
2793
                                              funcname)(*args,
2772
2794
                                                        **kwargs)))
2773
2795
 
2774
 
        if command == 'getattr':
 
2796
        if command == "getattr":
2775
2797
            attrname = request[1]
2776
2798
            if isinstance(client_object.__getattribute__(attrname),
2777
2799
                          collections.abc.Callable):
2778
 
                parent_pipe.send(('function', ))
 
2800
                parent_pipe.send(("function", ))
2779
2801
            else:
2780
2802
                parent_pipe.send((
2781
 
                    'data', client_object.__getattribute__(attrname)))
 
2803
                    "data", client_object.__getattribute__(attrname)))
2782
2804
 
2783
 
        if command == 'setattr':
 
2805
        if command == "setattr":
2784
2806
            attrname = request[1]
2785
2807
            value = request[2]
2786
2808
            setattr(client_object, attrname, value)
2892
2914
def string_to_delta(interval):
2893
2915
    """Parse a string and return a datetime.timedelta
2894
2916
 
2895
 
    >>> string_to_delta('7d') == datetime.timedelta(7)
2896
 
    True
2897
 
    >>> string_to_delta('60s') == datetime.timedelta(0, 60)
2898
 
    True
2899
 
    >>> string_to_delta('60m') == datetime.timedelta(0, 3600)
2900
 
    True
2901
 
    >>> string_to_delta('24h') == datetime.timedelta(1)
2902
 
    True
2903
 
    >>> string_to_delta('1w') == datetime.timedelta(7)
2904
 
    True
2905
 
    >>> 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)
2906
2928
    True
2907
2929
    """
2908
2930
 
3112
3134
 
3113
3135
    if server_settings["servicename"] != "Mandos":
3114
3136
        syslogger.setFormatter(
3115
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
3116
 
                              ' %(levelname)s: %(message)s'.format(
 
3137
            logging.Formatter("Mandos ({}) [%(process)d]:"
 
3138
                              " %(levelname)s: %(message)s".format(
3117
3139
                                  server_settings["servicename"])))
3118
3140
 
3119
3141
    # Parse config file with clients
3179
3201
 
3180
3202
        @gnutls.log_func
3181
3203
        def debug_gnutls(level, string):
3182
 
            logger.debug("GnuTLS: %s", string[:-1])
 
3204
            logger.debug("GnuTLS: %s",
 
3205
                         string[:-1].decode("utf-8",
 
3206
                                            errors="replace"))
3183
3207
 
3184
3208
        gnutls.global_set_log_function(debug_gnutls)
3185
3209
 
3560
3584
 
3561
3585
        try:
3562
3586
            with tempfile.NamedTemporaryFile(
3563
 
                    mode='wb',
 
3587
                    mode="wb",
3564
3588
                    suffix=".pickle",
3565
 
                    prefix='clients-',
 
3589
                    prefix="clients-",
3566
3590
                    dir=os.path.dirname(stored_state_path),
3567
3591
                    delete=False) as stored_state:
3568
3592
                pickle.dump((clients, client_settings), stored_state,
3655
3679
 
3656
3680
def should_only_run_tests():
3657
3681
    parser = argparse.ArgumentParser(add_help=False)
3658
 
    parser.add_argument("--check", action='store_true')
 
3682
    parser.add_argument("--check", action="store_true")
3659
3683
    args, unknown_args = parser.parse_known_args()
3660
3684
    run_tests = args.check
3661
3685
    if run_tests:
3669
3693
    tests.addTests(doctest.DocTestSuite())
3670
3694
    return tests
3671
3695
 
3672
 
if __name__ == '__main__':
 
3696
if __name__ == "__main__":
3673
3697
    try:
3674
3698
        if should_only_run_tests():
3675
3699
            # Call using ./mandos --check [--verbose]