/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: 2019-08-24 14:43:51 UTC
  • Revision ID: teddy@recompile.se-20190824144351-2y0l31jpj496vrtu
Server: Add scaffolding for tests

* mandos: Add code to run tests via the unittest module, similar to
          the code in mandos-ctl.  Also shut down logging on exit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8 -*-
 
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.
5
5
#
11
11
# "AvahiService" class, and some lines in "main".
12
12
#
13
13
# Everything else is
14
 
# Copyright © 2008-2017 Teddy Hogeborn
15
 
# Copyright © 2008-2017 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
#
77
77
import itertools
78
78
import collections
79
79
import codecs
 
80
import unittest
80
81
 
81
82
import dbus
82
83
import dbus.service
 
84
import gi
83
85
from gi.repository import GLib
84
86
from dbus.mainloop.glib import DBusGMainLoop
85
87
import ctypes
87
89
import xml.dom.minidom
88
90
import inspect
89
91
 
 
92
if sys.version_info.major == 2:
 
93
    __metaclass__ = type
 
94
 
90
95
# Try to find the value of SO_BINDTODEVICE:
91
96
try:
92
97
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
115
120
if sys.version_info.major == 2:
116
121
    str = unicode
117
122
 
118
 
version = "1.7.15"
 
123
if sys.version_info < (3, 2):
 
124
    configparser.Configparser = configparser.SafeConfigParser
 
125
 
 
126
version = "1.8.8"
119
127
stored_state_file = "clients.pickle"
120
128
 
121
129
logger = logging.getLogger()
179
187
    pass
180
188
 
181
189
 
182
 
class PGPEngine(object):
 
190
class PGPEngine:
183
191
    """A simple class for OpenPGP symmetric encryption & decryption"""
184
192
 
185
193
    def __init__(self):
275
283
 
276
284
 
277
285
# Pretend that we have an Avahi module
278
 
class Avahi(object):
279
 
    """This isn't so much a class as it is a module-like namespace.
280
 
    It is instantiated once, and simulates having an Avahi module."""
 
286
class avahi:
 
287
    """This isn't so much a class as it is a module-like namespace."""
281
288
    IF_UNSPEC = -1               # avahi-common/address.h
282
289
    PROTO_UNSPEC = -1            # avahi-common/address.h
283
290
    PROTO_INET = 0               # avahi-common/address.h
287
294
    DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
288
295
    DBUS_PATH_SERVER = "/"
289
296
 
290
 
    def string_array_to_txt_array(self, t):
 
297
    @staticmethod
 
298
    def string_array_to_txt_array(t):
291
299
        return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
292
300
                           for s in t), signature="ay")
293
301
    ENTRY_GROUP_ESTABLISHED = 2  # avahi-common/defs.h
298
306
    SERVER_RUNNING = 2           # avahi-common/defs.h
299
307
    SERVER_COLLISION = 3         # avahi-common/defs.h
300
308
    SERVER_FAILURE = 4           # avahi-common/defs.h
301
 
avahi = Avahi()
302
309
 
303
310
 
304
311
class AvahiError(Exception):
316
323
    pass
317
324
 
318
325
 
319
 
class AvahiService(object):
 
326
class AvahiService:
320
327
    """An Avahi (Zeroconf) service.
321
328
 
322
329
    Attributes:
496
503
class AvahiServiceToSyslog(AvahiService):
497
504
    def rename(self, *args, **kwargs):
498
505
        """Add the new name to the syslog messages"""
499
 
        ret = AvahiService.rename(self, *args, **kwargs)
 
506
        ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
500
507
        syslogger.setFormatter(logging.Formatter(
501
508
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
502
509
            .format(self.name)))
504
511
 
505
512
 
506
513
# Pretend that we have a GnuTLS module
507
 
class GnuTLS(object):
508
 
    """This isn't so much a class as it is a module-like namespace.
509
 
    It is instantiated once, and simulates having a GnuTLS module."""
 
514
class gnutls:
 
515
    """This isn't so much a class as it is a module-like namespace."""
510
516
 
511
517
    library = ctypes.util.find_library("gnutls")
512
518
    if library is None:
513
519
        library = ctypes.util.find_library("gnutls-deb0")
514
520
    _library = ctypes.cdll.LoadLibrary(library)
515
521
    del library
516
 
    _need_version = b"3.3.0"
517
 
 
518
 
    def __init__(self):
519
 
        # Need to use "self" here, since this method is called before
520
 
        # the assignment to the "gnutls" global variable happens.
521
 
        if self.check_version(self._need_version) is None:
522
 
            raise self.Error("Needs GnuTLS {} or later"
523
 
                             .format(self._need_version))
524
522
 
525
523
    # Unless otherwise indicated, the constants and types below are
526
524
    # all from the gnutls/gnutls.h C header file.
530
528
    E_INTERRUPTED = -52
531
529
    E_AGAIN = -28
532
530
    CRT_OPENPGP = 2
 
531
    CRT_RAWPK = 3
533
532
    CLIENT = 2
534
533
    SHUT_RDWR = 0
535
534
    CRD_CERTIFICATE = 1
536
535
    E_NO_CERTIFICATE_FOUND = -49
 
536
    X509_FMT_DER = 0
 
537
    NO_TICKETS = 1<<10
 
538
    ENABLE_RAWPK = 1<<18
 
539
    CTYPE_PEERS = 3
 
540
    KEYID_USE_SHA256 = 1        # gnutls/x509.h
537
541
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
538
542
 
539
543
    # Types
562
566
 
563
567
    # Exceptions
564
568
    class Error(Exception):
565
 
        # We need to use the class name "GnuTLS" here, since this
566
 
        # exception might be raised from within GnuTLS.__init__,
567
 
        # which is called before the assignment to the "gnutls"
568
 
        # global variable has happened.
569
569
        def __init__(self, message=None, code=None, args=()):
570
570
            # Default usage is by a message string, but if a return
571
571
            # code is passed, convert it to a string with
572
572
            # gnutls.strerror()
573
573
            self.code = code
574
574
            if message is None and code is not None:
575
 
                message = GnuTLS.strerror(code)
576
 
            return super(GnuTLS.Error, self).__init__(
 
575
                message = gnutls.strerror(code)
 
576
            return super(gnutls.Error, self).__init__(
577
577
                message, *args)
578
578
 
579
579
    class CertificateSecurityError(Error):
580
580
        pass
581
581
 
582
582
    # Classes
583
 
    class Credentials(object):
 
583
    class Credentials:
584
584
        def __init__(self):
585
585
            self._c_object = gnutls.certificate_credentials_t()
586
586
            gnutls.certificate_allocate_credentials(
590
590
        def __del__(self):
591
591
            gnutls.certificate_free_credentials(self._c_object)
592
592
 
593
 
    class ClientSession(object):
 
593
    class ClientSession:
594
594
        def __init__(self, socket, credentials=None):
595
595
            self._c_object = gnutls.session_t()
596
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
 
596
            gnutls_flags = gnutls.CLIENT
 
597
            if gnutls.check_version(b"3.5.6"):
 
598
                gnutls_flags |= gnutls.NO_TICKETS
 
599
            if gnutls.has_rawpk:
 
600
                gnutls_flags |= gnutls.ENABLE_RAWPK
 
601
            gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
 
602
            del gnutls_flags
597
603
            gnutls.set_default_priority(self._c_object)
598
604
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
599
605
            gnutls.handshake_set_private_extensions(self._c_object,
731
737
    check_version.argtypes = [ctypes.c_char_p]
732
738
    check_version.restype = ctypes.c_char_p
733
739
 
734
 
    # All the function declarations below are from gnutls/openpgp.h
735
 
 
736
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
737
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
738
 
    openpgp_crt_init.restype = _error_code
739
 
 
740
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
741
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
742
 
                                   ctypes.POINTER(datum_t),
743
 
                                   openpgp_crt_fmt_t]
744
 
    openpgp_crt_import.restype = _error_code
745
 
 
746
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
747
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
748
 
                                        ctypes.POINTER(ctypes.c_uint)]
749
 
    openpgp_crt_verify_self.restype = _error_code
750
 
 
751
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
752
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
753
 
    openpgp_crt_deinit.restype = None
754
 
 
755
 
    openpgp_crt_get_fingerprint = (
756
 
        _library.gnutls_openpgp_crt_get_fingerprint)
757
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
758
 
                                            ctypes.c_void_p,
759
 
                                            ctypes.POINTER(
760
 
                                                ctypes.c_size_t)]
761
 
    openpgp_crt_get_fingerprint.restype = _error_code
 
740
    _need_version = b"3.3.0"
 
741
    if check_version(_need_version) is None:
 
742
        raise self.Error("Needs GnuTLS {} or later"
 
743
                         .format(_need_version))
 
744
 
 
745
    _tls_rawpk_version = b"3.6.6"
 
746
    has_rawpk = bool(check_version(_tls_rawpk_version))
 
747
 
 
748
    if has_rawpk:
 
749
        # Types
 
750
        class pubkey_st(ctypes.Structure):
 
751
            _fields = []
 
752
        pubkey_t = ctypes.POINTER(pubkey_st)
 
753
 
 
754
        x509_crt_fmt_t = ctypes.c_int
 
755
 
 
756
        # All the function declarations below are from gnutls/abstract.h
 
757
        pubkey_init = _library.gnutls_pubkey_init
 
758
        pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
 
759
        pubkey_init.restype = _error_code
 
760
 
 
761
        pubkey_import = _library.gnutls_pubkey_import
 
762
        pubkey_import.argtypes = [pubkey_t, ctypes.POINTER(datum_t),
 
763
                                  x509_crt_fmt_t]
 
764
        pubkey_import.restype = _error_code
 
765
 
 
766
        pubkey_get_key_id = _library.gnutls_pubkey_get_key_id
 
767
        pubkey_get_key_id.argtypes = [pubkey_t, ctypes.c_int,
 
768
                                      ctypes.POINTER(ctypes.c_ubyte),
 
769
                                      ctypes.POINTER(ctypes.c_size_t)]
 
770
        pubkey_get_key_id.restype = _error_code
 
771
 
 
772
        pubkey_deinit = _library.gnutls_pubkey_deinit
 
773
        pubkey_deinit.argtypes = [pubkey_t]
 
774
        pubkey_deinit.restype = None
 
775
    else:
 
776
        # All the function declarations below are from gnutls/openpgp.h
 
777
 
 
778
        openpgp_crt_init = _library.gnutls_openpgp_crt_init
 
779
        openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
 
780
        openpgp_crt_init.restype = _error_code
 
781
 
 
782
        openpgp_crt_import = _library.gnutls_openpgp_crt_import
 
783
        openpgp_crt_import.argtypes = [openpgp_crt_t,
 
784
                                       ctypes.POINTER(datum_t),
 
785
                                       openpgp_crt_fmt_t]
 
786
        openpgp_crt_import.restype = _error_code
 
787
 
 
788
        openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
 
789
        openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
 
790
                                            ctypes.POINTER(ctypes.c_uint)]
 
791
        openpgp_crt_verify_self.restype = _error_code
 
792
 
 
793
        openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
 
794
        openpgp_crt_deinit.argtypes = [openpgp_crt_t]
 
795
        openpgp_crt_deinit.restype = None
 
796
 
 
797
        openpgp_crt_get_fingerprint = (
 
798
            _library.gnutls_openpgp_crt_get_fingerprint)
 
799
        openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
 
800
                                                ctypes.c_void_p,
 
801
                                                ctypes.POINTER(
 
802
                                                    ctypes.c_size_t)]
 
803
        openpgp_crt_get_fingerprint.restype = _error_code
 
804
 
 
805
    if check_version(b"3.6.4"):
 
806
        certificate_type_get2 = _library.gnutls_certificate_type_get2
 
807
        certificate_type_get2.argtypes = [session_t, ctypes.c_int]
 
808
        certificate_type_get2.restype = _error_code
762
809
 
763
810
    # Remove non-public functions
764
811
    del _error_code, _retry_on_error
765
 
# Create the global "gnutls" object, simulating a module
766
 
gnutls = GnuTLS()
767
812
 
768
813
 
769
814
def call_pipe(connection,       # : multiprocessing.Connection
777
822
    connection.close()
778
823
 
779
824
 
780
 
class Client(object):
 
825
class Client:
781
826
    """A representation of a client host served by this server.
782
827
 
783
828
    Attributes:
784
829
    approved:   bool(); 'None' if not yet approved/disapproved
785
830
    approval_delay: datetime.timedelta(); Time to wait for approval
786
831
    approval_duration: datetime.timedelta(); Duration of one approval
787
 
    checker:    subprocess.Popen(); a running checker process used
788
 
                                    to see if the client lives.
789
 
                                    'None' if no process is running.
 
832
    checker: multiprocessing.Process(); a running checker process used
 
833
             to see if the client lives. 'None' if no process is
 
834
             running.
790
835
    checker_callback_tag: a GLib event source tag, or None
791
836
    checker_command: string; External command which is run to check
792
837
                     if client lives.  %() expansions are done at
800
845
    disable_initiator_tag: a GLib event source tag, or None
801
846
    enabled:    bool()
802
847
    fingerprint: string (40 or 32 hexadecimal digits); used to
803
 
                 uniquely identify the client
 
848
                 uniquely identify an OpenPGP client
 
849
    key_id: string (64 hexadecimal digits); used to uniquely identify
 
850
            a client using raw public keys
804
851
    host:       string; available for use by the checker command
805
852
    interval:   datetime.timedelta(); How often to start a new checker
806
853
    last_approval_request: datetime.datetime(); (UTC) or None
824
871
    """
825
872
 
826
873
    runtime_expansions = ("approval_delay", "approval_duration",
827
 
                          "created", "enabled", "expires",
 
874
                          "created", "enabled", "expires", "key_id",
828
875
                          "fingerprint", "host", "interval",
829
876
                          "last_approval_request", "last_checked_ok",
830
877
                          "last_enabled", "name", "timeout")
860
907
            client["enabled"] = config.getboolean(client_name,
861
908
                                                  "enabled")
862
909
 
863
 
            # Uppercase and remove spaces from fingerprint for later
864
 
            # comparison purposes with return value from the
865
 
            # fingerprint() function
 
910
            # Uppercase and remove spaces from key_id and fingerprint
 
911
            # for later comparison purposes with return value from the
 
912
            # key_id() and fingerprint() functions
 
913
            client["key_id"] = (section.get("key_id", "").upper()
 
914
                                .replace(" ", ""))
866
915
            client["fingerprint"] = (section["fingerprint"].upper()
867
916
                                     .replace(" ", ""))
868
917
            if "secret" in section:
912
961
            self.expires = None
913
962
 
914
963
        logger.debug("Creating client %r", self.name)
 
964
        logger.debug("  Key ID: %s", self.key_id)
915
965
        logger.debug("  Fingerprint: %s", self.fingerprint)
916
966
        self.created = settings.get("created",
917
967
                                    datetime.datetime.utcnow())
994
1044
    def checker_callback(self, source, condition, connection,
995
1045
                         command):
996
1046
        """The checker has completed, so take appropriate actions."""
997
 
        self.checker_callback_tag = None
998
 
        self.checker = None
999
1047
        # Read return code from connection (see call_pipe)
1000
1048
        returncode = connection.recv()
1001
1049
        connection.close()
 
1050
        self.checker.join()
 
1051
        self.checker_callback_tag = None
 
1052
        self.checker = None
1002
1053
 
1003
1054
        if returncode >= 0:
1004
1055
            self.last_checker_status = returncode
1999
2050
    def Name_dbus_property(self):
2000
2051
        return dbus.String(self.name)
2001
2052
 
 
2053
    # KeyID - property
 
2054
    @dbus_annotations(
 
2055
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
 
2056
    @dbus_service_property(_interface, signature="s", access="read")
 
2057
    def KeyID_dbus_property(self):
 
2058
        return dbus.String(self.key_id)
 
2059
 
2002
2060
    # Fingerprint - property
2003
2061
    @dbus_annotations(
2004
2062
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
2159
2217
    del _interface
2160
2218
 
2161
2219
 
2162
 
class ProxyClient(object):
2163
 
    def __init__(self, child_pipe, fpr, address):
 
2220
class ProxyClient:
 
2221
    def __init__(self, child_pipe, key_id, fpr, address):
2164
2222
        self._pipe = child_pipe
2165
 
        self._pipe.send(('init', fpr, address))
 
2223
        self._pipe.send(('init', key_id, fpr, address))
2166
2224
        if not self._pipe.recv():
2167
 
            raise KeyError(fpr)
 
2225
            raise KeyError(key_id or fpr)
2168
2226
 
2169
2227
    def __getattribute__(self, name):
2170
2228
        if name == '_pipe':
2237
2295
 
2238
2296
            approval_required = False
2239
2297
            try:
2240
 
                try:
2241
 
                    fpr = self.fingerprint(
2242
 
                        self.peer_certificate(session))
2243
 
                except (TypeError, gnutls.Error) as error:
2244
 
                    logger.warning("Bad certificate: %s", error)
2245
 
                    return
2246
 
                logger.debug("Fingerprint: %s", fpr)
2247
 
 
2248
 
                try:
2249
 
                    client = ProxyClient(child_pipe, fpr,
 
2298
                if gnutls.has_rawpk:
 
2299
                    fpr = b""
 
2300
                    try:
 
2301
                        key_id = self.key_id(
 
2302
                            self.peer_certificate(session))
 
2303
                    except (TypeError, gnutls.Error) as error:
 
2304
                        logger.warning("Bad certificate: %s", error)
 
2305
                        return
 
2306
                    logger.debug("Key ID: %s", key_id)
 
2307
 
 
2308
                else:
 
2309
                    key_id = b""
 
2310
                    try:
 
2311
                        fpr = self.fingerprint(
 
2312
                            self.peer_certificate(session))
 
2313
                    except (TypeError, gnutls.Error) as error:
 
2314
                        logger.warning("Bad certificate: %s", error)
 
2315
                        return
 
2316
                    logger.debug("Fingerprint: %s", fpr)
 
2317
 
 
2318
                try:
 
2319
                    client = ProxyClient(child_pipe, key_id, fpr,
2250
2320
                                         self.client_address)
2251
2321
                except KeyError:
2252
2322
                    return
2329
2399
 
2330
2400
    @staticmethod
2331
2401
    def peer_certificate(session):
2332
 
        "Return the peer's OpenPGP certificate as a bytestring"
2333
 
        # If not an OpenPGP certificate...
2334
 
        if (gnutls.certificate_type_get(session._c_object)
2335
 
            != gnutls.CRT_OPENPGP):
 
2402
        "Return the peer's certificate as a bytestring"
 
2403
        try:
 
2404
            cert_type = gnutls.certificate_type_get2(session._c_object,
 
2405
                                                     gnutls.CTYPE_PEERS)
 
2406
        except AttributeError:
 
2407
            cert_type = gnutls.certificate_type_get(session._c_object)
 
2408
        if gnutls.has_rawpk:
 
2409
            valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
 
2410
        else:
 
2411
            valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
 
2412
        # If not a valid certificate type...
 
2413
        if cert_type not in valid_cert_types:
 
2414
            logger.info("Cert type %r not in %r", cert_type,
 
2415
                        valid_cert_types)
2336
2416
            # ...return invalid data
2337
2417
            return b""
2338
2418
        list_size = ctypes.c_uint(1)
2346
2426
        return ctypes.string_at(cert.data, cert.size)
2347
2427
 
2348
2428
    @staticmethod
 
2429
    def key_id(certificate):
 
2430
        "Convert a certificate bytestring to a hexdigit key ID"
 
2431
        # New GnuTLS "datum" with the public key
 
2432
        datum = gnutls.datum_t(
 
2433
            ctypes.cast(ctypes.c_char_p(certificate),
 
2434
                        ctypes.POINTER(ctypes.c_ubyte)),
 
2435
            ctypes.c_uint(len(certificate)))
 
2436
        # XXX all these need to be created in the gnutls "module"
 
2437
        # New empty GnuTLS certificate
 
2438
        pubkey = gnutls.pubkey_t()
 
2439
        gnutls.pubkey_init(ctypes.byref(pubkey))
 
2440
        # Import the raw public key into the certificate
 
2441
        gnutls.pubkey_import(pubkey,
 
2442
                             ctypes.byref(datum),
 
2443
                             gnutls.X509_FMT_DER)
 
2444
        # New buffer for the key ID
 
2445
        buf = ctypes.create_string_buffer(32)
 
2446
        buf_len = ctypes.c_size_t(len(buf))
 
2447
        # Get the key ID from the raw public key into the buffer
 
2448
        gnutls.pubkey_get_key_id(pubkey,
 
2449
                                 gnutls.KEYID_USE_SHA256,
 
2450
                                 ctypes.cast(ctypes.byref(buf),
 
2451
                                             ctypes.POINTER(ctypes.c_ubyte)),
 
2452
                                 ctypes.byref(buf_len))
 
2453
        # Deinit the certificate
 
2454
        gnutls.pubkey_deinit(pubkey)
 
2455
 
 
2456
        # Convert the buffer to a Python bytestring
 
2457
        key_id = ctypes.string_at(buf, buf_len.value)
 
2458
        # Convert the bytestring to hexadecimal notation
 
2459
        hex_key_id = binascii.hexlify(key_id).upper()
 
2460
        return hex_key_id
 
2461
 
 
2462
    @staticmethod
2349
2463
    def fingerprint(openpgp):
2350
2464
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2351
2465
        # New GnuTLS "datum" with the OpenPGP public key
2365
2479
                                       ctypes.byref(crtverify))
2366
2480
        if crtverify.value != 0:
2367
2481
            gnutls.openpgp_crt_deinit(crt)
2368
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
2482
            raise gnutls.CertificateSecurityError(code
 
2483
                                                  =crtverify.value)
2369
2484
        # New buffer for the fingerprint
2370
2485
        buf = ctypes.create_string_buffer(20)
2371
2486
        buf_len = ctypes.c_size_t()
2381
2496
        return hex_fpr
2382
2497
 
2383
2498
 
2384
 
class MultiprocessingMixIn(object):
 
2499
class MultiprocessingMixIn:
2385
2500
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2386
2501
 
2387
2502
    def sub_process_main(self, request, address):
2399
2514
        return proc
2400
2515
 
2401
2516
 
2402
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
 
2517
class MultiprocessingMixInWithPipe(MultiprocessingMixIn):
2403
2518
    """ adds a pipe to the MixIn """
2404
2519
 
2405
2520
    def process_request(self, request, client_address):
2420
2535
 
2421
2536
 
2422
2537
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2423
 
                     socketserver.TCPServer, object):
 
2538
                     socketserver.TCPServer):
2424
2539
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
2425
2540
 
2426
2541
    Attributes:
2499
2614
                    raise
2500
2615
        # Only bind(2) the socket if we really need to.
2501
2616
        if self.server_address[0] or self.server_address[1]:
 
2617
            if self.server_address[1]:
 
2618
                self.allow_reuse_address = True
2502
2619
            if not self.server_address[0]:
2503
2620
                if self.address_family == socket.AF_INET6:
2504
2621
                    any_address = "::"  # in6addr_any
2578
2695
        command = request[0]
2579
2696
 
2580
2697
        if command == 'init':
2581
 
            fpr = request[1]
2582
 
            address = request[2]
 
2698
            key_id = request[1].decode("ascii")
 
2699
            fpr = request[2].decode("ascii")
 
2700
            address = request[3]
2583
2701
 
2584
2702
            for c in self.clients.values():
2585
 
                if c.fingerprint == fpr:
 
2703
                if key_id == "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855":
 
2704
                    continue
 
2705
                if key_id and c.key_id == key_id:
 
2706
                    client = c
 
2707
                    break
 
2708
                if fpr and c.fingerprint == fpr:
2586
2709
                    client = c
2587
2710
                    break
2588
2711
            else:
2589
 
                logger.info("Client not found for fingerprint: %s, ad"
2590
 
                            "dress: %s", fpr, address)
 
2712
                logger.info("Client not found for key ID: %s, address"
 
2713
                            ": %s", key_id or fpr, address)
2591
2714
                if self.use_dbus:
2592
2715
                    # Emit D-Bus signal
2593
 
                    mandos_dbus_service.ClientNotFound(fpr,
 
2716
                    mandos_dbus_service.ClientNotFound(key_id or fpr,
2594
2717
                                                       address[0])
2595
2718
                parent_pipe.send(False)
2596
2719
                return False
2853
2976
 
2854
2977
    options = parser.parse_args()
2855
2978
 
2856
 
    if options.check:
2857
 
        import doctest
2858
 
        fail_count, test_count = doctest.testmod()
2859
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2860
 
 
2861
2979
    # Default values for config file for server-global settings
 
2980
    if gnutls.has_rawpk:
 
2981
        priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA"
 
2982
                    ":!VERS-ALL:+VERS-TLS1.3:%PROFILE_ULTRA")
 
2983
    else:
 
2984
        priority = ("SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
 
2985
                    ":+SIGN-DSA-SHA256")
2862
2986
    server_defaults = {"interface": "",
2863
2987
                       "address": "",
2864
2988
                       "port": "",
2865
2989
                       "debug": "False",
2866
 
                       "priority":
2867
 
                       "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2868
 
                       ":+SIGN-DSA-SHA256",
 
2990
                       "priority": priority,
2869
2991
                       "servicename": "Mandos",
2870
2992
                       "use_dbus": "True",
2871
2993
                       "use_ipv6": "True",
2876
2998
                       "foreground": "False",
2877
2999
                       "zeroconf": "True",
2878
3000
                       }
 
3001
    del priority
2879
3002
 
2880
3003
    # Parse config file for server-global settings
2881
 
    server_config = configparser.SafeConfigParser(server_defaults)
 
3004
    server_config = configparser.ConfigParser(server_defaults)
2882
3005
    del server_defaults
2883
3006
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
2884
 
    # Convert the SafeConfigParser object to a dict
 
3007
    # Convert the ConfigParser object to a dict
2885
3008
    server_settings = server_config.defaults()
2886
3009
    # Use the appropriate methods on the non-string config options
2887
3010
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2959
3082
                                  server_settings["servicename"])))
2960
3083
 
2961
3084
    # Parse config file with clients
2962
 
    client_config = configparser.SafeConfigParser(Client
2963
 
                                                  .client_defaults)
 
3085
    client_config = configparser.ConfigParser(Client.client_defaults)
2964
3086
    client_config.read(os.path.join(server_settings["configdir"],
2965
3087
                                    "clients.conf"))
2966
3088
 
3037
3159
        # Close all input and output, do double fork, etc.
3038
3160
        daemon()
3039
3161
 
3040
 
    # multiprocessing will use threads, so before we use GLib we need
3041
 
    # to inform GLib that threads will be used.
3042
 
    GLib.threads_init()
 
3162
    if gi.version_info < (3, 10, 2):
 
3163
        # multiprocessing will use threads, so before we use GLib we
 
3164
        # need to inform GLib that threads will be used.
 
3165
        GLib.threads_init()
3043
3166
 
3044
3167
    global main_loop
3045
3168
    # From the Avahi example code
3125
3248
                        for k in ("name", "host"):
3126
3249
                            if isinstance(value[k], bytes):
3127
3250
                                value[k] = value[k].decode("utf-8")
 
3251
                        if "key_id" not in value:
 
3252
                            value["key_id"] = ""
 
3253
                        elif "fingerprint" not in value:
 
3254
                            value["fingerprint"] = ""
3128
3255
                    #  old_client_settings
3129
3256
                    # .keys()
3130
3257
                    old_client_settings = {
3267
3394
                pass
3268
3395
 
3269
3396
            @dbus.service.signal(_interface, signature="ss")
3270
 
            def ClientNotFound(self, fingerprint, address):
 
3397
            def ClientNotFound(self, key_id, address):
3271
3398
                "D-Bus signal"
3272
3399
                pass
3273
3400
 
3488
3615
    # Must run before the D-Bus bus name gets deregistered
3489
3616
    cleanup()
3490
3617
 
 
3618
 
 
3619
def should_only_run_tests():
 
3620
    parser = argparse.ArgumentParser(add_help=False)
 
3621
    parser.add_argument("--check", action='store_true')
 
3622
    args, unknown_args = parser.parse_known_args()
 
3623
    run_tests = args.check
 
3624
    if run_tests:
 
3625
        # Remove --check argument from sys.argv
 
3626
        sys.argv[1:] = unknown_args
 
3627
    return run_tests
 
3628
 
 
3629
# Add all tests from doctest strings
 
3630
def load_tests(loader, tests, none):
 
3631
    import doctest
 
3632
    tests.addTests(doctest.DocTestSuite())
 
3633
    return tests
3491
3634
 
3492
3635
if __name__ == '__main__':
3493
 
    main()
 
3636
    try:
 
3637
        if should_only_run_tests():
 
3638
            # Call using ./mandos --check [--verbose]
 
3639
            unittest.main()
 
3640
        else:
 
3641
            main()
 
3642
    finally:
 
3643
        logging.shutdown()