/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: 2016-02-28 03:01:43 UTC
  • Revision ID: teddy@recompile.se-20160228030143-i6w90r7wzkvlx9kq
Stop using python-gnutls.  Use GnuTLS 3.3 or later directly.

* INSTALL: Document dependency on GnuTLS 3.3 and remove dependency on
          Python-GnuTLS.

* debian/control (Source: mandos/Build-Depends): Add (>= 3.3.0) to
                                                 "libgnutls28-dev" and
                                                 "gnutls-dev".
  (Source: mandos/Build-Depends-Indep): Remove "python2.7-gnutls".
  (Package: mandos/Depends): Remove "python-gnutls" and
                             "python2.7-gnutls", add "libgnutls28-dev
                             (>= 3.3.0) | libgnutls30 (>= 3.3.0)"
* mandos: Remove imports of "gnutls" and all submodules.
  (GnuTLS, gnutls): New; simulate a "gnutls" module.  Change all
                    callers to match new shorter names.

Show diffs side-by-side

added added

removed removed

Lines of Context:
44
44
import argparse
45
45
import datetime
46
46
import errno
47
 
import gnutls.connection
48
 
import gnutls.errors
49
 
import gnutls.library.functions
50
 
import gnutls.library.constants
51
 
import gnutls.library.types
52
47
try:
53
48
    import ConfigParser as configparser
54
49
except ImportError:
434
429
            .format(self.name)))
435
430
        return ret
436
431
 
 
432
# Pretend that we have a GnuTLS module
 
433
class GnuTLS(object):
 
434
    """This isn't so much a class as it is a module-like namespace.
 
435
    It is instantiated once, and simulates having a GnuTLS module."""
 
436
    
 
437
    _library = ctypes.cdll.LoadLibrary(
 
438
        ctypes.util.find_library("gnutls"))
 
439
    _need_version = "3.3.0"
 
440
    def __init__(self):
 
441
        # Need to use class name "GnuTLS" here, since this method is
 
442
        # called before the assignment to the "gnutls" global variable
 
443
        # happens.
 
444
        if GnuTLS.check_version(self._need_version) is None:
 
445
            raise GnuTLS.Error("Needs GnuTLS {} or later"
 
446
                               .format(self._need_version))
 
447
    
 
448
    # Unless otherwise indicated, the constants and types below are
 
449
    # all from the gnutls/gnutls.h C header file.
 
450
    
 
451
    # Constants
 
452
    E_SUCCESS = 0
 
453
    CRT_OPENPGP = 2
 
454
    CLIENT = 2
 
455
    SHUT_RDWR = 0
 
456
    CRD_CERTIFICATE = 1
 
457
    E_NO_CERTIFICATE_FOUND = -49
 
458
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
 
459
    
 
460
    # Types
 
461
    class session_int(ctypes.Structure):
 
462
        _fields_ = []
 
463
    session_t = ctypes.POINTER(session_int)
 
464
    class certificate_credentials_st(ctypes.Structure):
 
465
        _fields_ = []
 
466
    certificate_credentials_t = ctypes.POINTER(
 
467
        certificate_credentials_st)
 
468
    certificate_type_t = ctypes.c_int
 
469
    class datum_t(ctypes.Structure):
 
470
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
 
471
                    ('size', ctypes.c_uint)]
 
472
    class openpgp_crt_int(ctypes.Structure):
 
473
        _fields_ = []
 
474
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
 
475
    openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
 
476
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
 
477
    credentials_type_t = ctypes.c_int # 
 
478
    transport_ptr_t = ctypes.c_void_p
 
479
    close_request_t = ctypes.c_int
 
480
    
 
481
    # Exceptions
 
482
    class Error(Exception):
 
483
        # We need to use the class name "GnuTLS" here, since this
 
484
        # exception might be raised from within GnuTLS.__init__,
 
485
        # which is called before the assignment to the "gnutls"
 
486
        # global variable happens.
 
487
        def __init__(self, message = None, code = None, args=()):
 
488
            # Default usage is by a message string, but if a return
 
489
            # code is passed, convert it to a string with
 
490
            # gnutls.strerror()
 
491
            if message is None and code is not None:
 
492
                message = GnuTLS.strerror(code)
 
493
            return super(GnuTLS.Error, self).__init__(
 
494
                message, *args)
 
495
    
 
496
    class CertificateSecurityError(Error):
 
497
        pass
 
498
    
 
499
    # Classes
 
500
    class Credentials(object):
 
501
        def __init__(self):
 
502
            self._c_object = gnutls.certificate_credentials_t()
 
503
            gnutls.certificate_allocate_credentials(
 
504
                ctypes.byref(self._c_object))
 
505
            self.type = gnutls.CRD_CERTIFICATE
 
506
        
 
507
        def __del__(self):
 
508
            gnutls.certificate_free_credentials(self._c_object)
 
509
    
 
510
    class ClientSession(object):
 
511
        def __init__(self, socket, credentials = None):
 
512
            self._c_object = gnutls.session_t()
 
513
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
 
514
            gnutls.set_default_priority(self._c_object)
 
515
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
 
516
            gnutls.handshake_set_private_extensions(self._c_object,
 
517
                                                    True)
 
518
            self.socket = socket
 
519
            if credentials is None:
 
520
                credentials = gnutls.Credentials()
 
521
            gnutls.credentials_set(self._c_object, credentials.type,
 
522
                                   ctypes.cast(credentials._c_object,
 
523
                                               ctypes.c_void_p))
 
524
            self.credentials = credentials
 
525
        
 
526
        def __del__(self):
 
527
            gnutls.deinit(self._c_object)
 
528
        
 
529
        def handshake(self):
 
530
            return gnutls.handshake(self._c_object)
 
531
        
 
532
        def send(self, data):
 
533
            data = bytes(data)
 
534
            if not data:
 
535
                return 0
 
536
            return gnutls.record_send(self._c_object, data, len(data))
 
537
        
 
538
        def bye(self):
 
539
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
 
540
    
 
541
    # Error handling function
 
542
    def _error_code(result):
 
543
        """A function to raise exceptions on errors, suitable
 
544
        for the 'restype' attribute on ctypes functions"""
 
545
        if result >= 0:
 
546
            return result
 
547
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
 
548
            raise gnutls.CertificateSecurityError(code = result)
 
549
        raise gnutls.Error(code = result)
 
550
    
 
551
    # Unless otherwise indicated, the function declarations below are
 
552
    # all from the gnutls/gnutls.h C header file.
 
553
    
 
554
    # Functions
 
555
    priority_set_direct = _library.gnutls_priority_set_direct
 
556
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
 
557
                                    ctypes.POINTER(ctypes.c_char_p)]
 
558
    priority_set_direct.restype = _error_code
 
559
    
 
560
    init = _library.gnutls_init
 
561
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
 
562
    init.restype = _error_code
 
563
    
 
564
    set_default_priority = _library.gnutls_set_default_priority
 
565
    set_default_priority.argtypes = [session_t]
 
566
    set_default_priority.restype = _error_code
 
567
    
 
568
    record_send = _library.gnutls_record_send
 
569
    record_send.argtypes = [session_t, ctypes.c_void_p,
 
570
                            ctypes.c_size_t]
 
571
    record_send.restype = ctypes.c_ssize_t
 
572
    
 
573
    certificate_allocate_credentials = (
 
574
        _library.gnutls_certificate_allocate_credentials)
 
575
    certificate_allocate_credentials.argtypes = [
 
576
        ctypes.POINTER(certificate_credentials_t)]
 
577
    certificate_allocate_credentials.restype = _error_code
 
578
    
 
579
    certificate_free_credentials = (
 
580
        _library.gnutls_certificate_free_credentials)
 
581
    certificate_free_credentials.argtypes = [certificate_credentials_t]
 
582
    certificate_free_credentials.restype = None
 
583
    
 
584
    handshake_set_private_extensions = (
 
585
        _library.gnutls_handshake_set_private_extensions)
 
586
    handshake_set_private_extensions.argtypes = [session_t,
 
587
                                                 ctypes.c_int]
 
588
    handshake_set_private_extensions.restype = None
 
589
    
 
590
    credentials_set = _library.gnutls_credentials_set
 
591
    credentials_set.argtypes = [session_t, credentials_type_t,
 
592
                                ctypes.c_void_p]
 
593
    credentials_set.restype = _error_code
 
594
    
 
595
    strerror = _library.gnutls_strerror
 
596
    strerror.argtypes = [ctypes.c_int]
 
597
    strerror.restype = ctypes.c_char_p
 
598
    
 
599
    certificate_type_get = _library.gnutls_certificate_type_get
 
600
    certificate_type_get.argtypes = [session_t]
 
601
    certificate_type_get.restype = _error_code
 
602
    
 
603
    certificate_get_peers = _library.gnutls_certificate_get_peers
 
604
    certificate_get_peers.argtypes = [session_t,
 
605
                                      ctypes.POINTER(ctypes.c_uint)]
 
606
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
 
607
    
 
608
    global_set_log_level = _library.gnutls_global_set_log_level
 
609
    global_set_log_level.argtypes = [ctypes.c_int]
 
610
    global_set_log_level.restype = None
 
611
    
 
612
    global_set_log_function = _library.gnutls_global_set_log_function
 
613
    global_set_log_function.argtypes = [log_func]
 
614
    global_set_log_function.restype = None
 
615
    
 
616
    deinit = _library.gnutls_deinit
 
617
    deinit.argtypes = [session_t]
 
618
    deinit.restype = None
 
619
    
 
620
    handshake = _library.gnutls_handshake
 
621
    handshake.argtypes = [session_t]
 
622
    handshake.restype = _error_code
 
623
    
 
624
    transport_set_ptr = _library.gnutls_transport_set_ptr
 
625
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
 
626
    transport_set_ptr.restype = None
 
627
    
 
628
    bye = _library.gnutls_bye
 
629
    bye.argtypes = [session_t, close_request_t]
 
630
    bye.restype = _error_code
 
631
    
 
632
    check_version = _library.gnutls_check_version
 
633
    check_version.argtypes = [ctypes.c_char_p]
 
634
    check_version.restype = ctypes.c_char_p
 
635
    
 
636
    # All the function declarations below are from gnutls/openpgp.h
 
637
    
 
638
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
 
639
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
 
640
    openpgp_crt_init.restype = _error_code
 
641
    
 
642
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
 
643
    openpgp_crt_import.argtypes = [openpgp_crt_t,
 
644
                                   ctypes.POINTER(datum_t),
 
645
                                   openpgp_crt_fmt_t]
 
646
    openpgp_crt_import.restype = _error_code
 
647
    
 
648
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
 
649
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
 
650
                                        ctypes.POINTER(ctypes.c_uint)]
 
651
    openpgp_crt_verify_self.restype = _error_code
 
652
    
 
653
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
 
654
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
 
655
    openpgp_crt_deinit.restype = None
 
656
    
 
657
    openpgp_crt_get_fingerprint = (
 
658
        _library.gnutls_openpgp_crt_get_fingerprint)
 
659
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
 
660
                                            ctypes.c_void_p,
 
661
                                            ctypes.POINTER(
 
662
                                                ctypes.c_size_t)]
 
663
    openpgp_crt_get_fingerprint.restype = _error_code
 
664
    
 
665
    # Remove non-public function
 
666
    del _error_code
 
667
# Create the global "gnutls" object, simulating a module
 
668
gnutls = GnuTLS()
 
669
 
437
670
def call_pipe(connection,       # : multiprocessing.Connection
438
671
              func, *args, **kwargs):
439
672
    """This function is meant to be called by multiprocessing.Process
1879
2112
            logger.debug("Pipe FD: %d",
1880
2113
                         self.server.child_pipe.fileno())
1881
2114
            
1882
 
            session = gnutls.connection.ClientSession(
1883
 
                self.request, gnutls.connection.X509Credentials())
1884
 
            
1885
 
            # Note: gnutls.connection.X509Credentials is really a
1886
 
            # generic GnuTLS certificate credentials object so long as
1887
 
            # no X.509 keys are added to it.  Therefore, we can use it
1888
 
            # here despite using OpenPGP certificates.
 
2115
            session = gnutls.ClientSession(self.request)
1889
2116
            
1890
2117
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1891
2118
            #                      "+AES-256-CBC", "+SHA1",
1895
2122
            priority = self.server.gnutls_priority
1896
2123
            if priority is None:
1897
2124
                priority = "NORMAL"
1898
 
            gnutls.library.functions.gnutls_priority_set_direct(
1899
 
                session._c_object, priority, None)
 
2125
            gnutls.priority_set_direct(session._c_object, priority,
 
2126
                                       None)
1900
2127
            
1901
2128
            # Start communication using the Mandos protocol
1902
2129
            # Get protocol number
1912
2139
            # Start GnuTLS connection
1913
2140
            try:
1914
2141
                session.handshake()
1915
 
            except gnutls.errors.GNUTLSError as error:
 
2142
            except gnutls.Error as error:
1916
2143
                logger.warning("Handshake failed: %s", error)
1917
2144
                # Do not run session.bye() here: the session is not
1918
2145
                # established.  Just abandon the request.
1924
2151
                try:
1925
2152
                    fpr = self.fingerprint(
1926
2153
                        self.peer_certificate(session))
1927
 
                except (TypeError,
1928
 
                        gnutls.errors.GNUTLSError) as error:
 
2154
                except (TypeError, gnutls.Error) as error:
1929
2155
                    logger.warning("Bad certificate: %s", error)
1930
2156
                    return
1931
2157
                logger.debug("Fingerprint: %s", fpr)
1993
2219
                while sent_size < len(client.secret):
1994
2220
                    try:
1995
2221
                        sent = session.send(client.secret[sent_size:])
1996
 
                    except gnutls.errors.GNUTLSError as error:
 
2222
                    except gnutls.Error as error:
1997
2223
                        logger.warning("gnutls send failed",
1998
2224
                                       exc_info=error)
1999
2225
                        return
2014
2240
                    client.approvals_pending -= 1
2015
2241
                try:
2016
2242
                    session.bye()
2017
 
                except gnutls.errors.GNUTLSError as error:
 
2243
                except gnutls.Error as error:
2018
2244
                    logger.warning("GnuTLS bye failed",
2019
2245
                                   exc_info=error)
2020
2246
    
2022
2248
    def peer_certificate(session):
2023
2249
        "Return the peer's OpenPGP certificate as a bytestring"
2024
2250
        # If not an OpenPGP certificate...
2025
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
2026
 
                session._c_object)
2027
 
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
2028
 
            # ...do the normal thing
2029
 
            return session.peer_certificate
 
2251
        if (gnutls.certificate_type_get(session._c_object)
 
2252
            != gnutls.CRT_OPENPGP):
 
2253
            # ...return invalid data
 
2254
            return b""
2030
2255
        list_size = ctypes.c_uint(1)
2031
 
        cert_list = (gnutls.library.functions
2032
 
                     .gnutls_certificate_get_peers
 
2256
        cert_list = (gnutls.certificate_get_peers
2033
2257
                     (session._c_object, ctypes.byref(list_size)))
2034
2258
        if not bool(cert_list) and list_size.value != 0:
2035
 
            raise gnutls.errors.GNUTLSError("error getting peer"
2036
 
                                            " certificate")
 
2259
            raise gnutls.Error("error getting peer certificate")
2037
2260
        if list_size.value == 0:
2038
2261
            return None
2039
2262
        cert = cert_list[0]
2043
2266
    def fingerprint(openpgp):
2044
2267
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2045
2268
        # New GnuTLS "datum" with the OpenPGP public key
2046
 
        datum = gnutls.library.types.gnutls_datum_t(
 
2269
        datum = gnutls.datum_t(
2047
2270
            ctypes.cast(ctypes.c_char_p(openpgp),
2048
2271
                        ctypes.POINTER(ctypes.c_ubyte)),
2049
2272
            ctypes.c_uint(len(openpgp)))
2050
2273
        # New empty GnuTLS certificate
2051
 
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
2052
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
2053
 
            ctypes.byref(crt))
 
2274
        crt = gnutls.openpgp_crt_t()
 
2275
        gnutls.openpgp_crt_init(ctypes.byref(crt))
2054
2276
        # Import the OpenPGP public key into the certificate
2055
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
2056
 
            crt, ctypes.byref(datum),
2057
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
2277
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
 
2278
                                  gnutls.OPENPGP_FMT_RAW)
2058
2279
        # Verify the self signature in the key
2059
2280
        crtverify = ctypes.c_uint()
2060
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
2061
 
            crt, 0, ctypes.byref(crtverify))
 
2281
        gnutls.openpgp_crt_verify_self(crt, 0,
 
2282
                                       ctypes.byref(crtverify))
2062
2283
        if crtverify.value != 0:
2063
 
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2064
 
            raise gnutls.errors.CertificateSecurityError(
2065
 
                "Verify failed")
 
2284
            gnutls.openpgp_crt_deinit(crt)
 
2285
            raise gnutls.CertificateSecurityError("Verify failed")
2066
2286
        # New buffer for the fingerprint
2067
2287
        buf = ctypes.create_string_buffer(20)
2068
2288
        buf_len = ctypes.c_size_t()
2069
2289
        # Get the fingerprint from the certificate into the buffer
2070
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
2071
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
2290
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
2291
                                           ctypes.byref(buf_len))
2072
2292
        # Deinit the certificate
2073
 
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
2293
        gnutls.openpgp_crt_deinit(crt)
2074
2294
        # Convert the buffer to a Python bytestring
2075
2295
        fpr = ctypes.string_at(buf, buf_len.value)
2076
2296
        # Convert the bytestring to hexadecimal notation
2702
2922
        
2703
2923
        # "Use a log level over 10 to enable all debugging options."
2704
2924
        # - GnuTLS manual
2705
 
        gnutls.library.functions.gnutls_global_set_log_level(11)
 
2925
        gnutls.global_set_log_level(11)
2706
2926
        
2707
 
        @gnutls.library.types.gnutls_log_func
 
2927
        @gnutls.log_func
2708
2928
        def debug_gnutls(level, string):
2709
2929
            logger.debug("GnuTLS: %s", string[:-1])
2710
2930
        
2711
 
        gnutls.library.functions.gnutls_global_set_log_function(
2712
 
            debug_gnutls)
 
2931
        gnutls.global_set_log_function(debug_gnutls)
2713
2932
        
2714
2933
        # Redirect stdin so all checkers get /dev/null
2715
2934
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)