/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2016-02-28 03:01:43 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 331.
  • 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.crypto
48
 
import gnutls.connection
49
 
import gnutls.errors
50
 
import gnutls.library.functions
51
 
import gnutls.library.constants
52
 
import gnutls.library.types
53
47
try:
54
48
    import ConfigParser as configparser
55
49
except ImportError:
104
98
if sys.version_info.major == 2:
105
99
    str = unicode
106
100
 
107
 
version = "1.6.9"
 
101
version = "1.7.1"
108
102
stored_state_file = "clients.pickle"
109
103
 
110
104
logger = logging.getLogger()
435
429
            .format(self.name)))
436
430
        return ret
437
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
 
438
670
def call_pipe(connection,       # : multiprocessing.Connection
439
671
              func, *args, **kwargs):
440
672
    """This function is meant to be called by multiprocessing.Process
842
1074
                           access="r")
843
1075
    def Property_dbus_property(self):
844
1076
        return dbus.Boolean(False)
 
1077
    
 
1078
    See also the DBusObjectWithAnnotations class.
845
1079
    """
846
1080
    
847
1081
    def decorator(func):
869
1103
    pass
870
1104
 
871
1105
 
872
 
class DBusObjectWithProperties(dbus.service.Object):
873
 
    """A D-Bus object with properties.
 
1106
class DBusObjectWithAnnotations(dbus.service.Object):
 
1107
    """A D-Bus object with annotations.
874
1108
    
875
 
    Classes inheriting from this can use the dbus_service_property
876
 
    decorator to expose methods as D-Bus properties.  It exposes the
877
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
 
1109
    Classes inheriting from this can use the dbus_annotations
 
1110
    decorator to add annotations to methods or signals.
878
1111
    """
879
1112
    
880
1113
    @staticmethod
896
1129
                for name, athing in
897
1130
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
898
1131
    
 
1132
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
 
1133
                         out_signature = "s",
 
1134
                         path_keyword = 'object_path',
 
1135
                         connection_keyword = 'connection')
 
1136
    def Introspect(self, object_path, connection):
 
1137
        """Overloading of standard D-Bus method.
 
1138
        
 
1139
        Inserts annotation tags on methods and signals.
 
1140
        """
 
1141
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
1142
                                                   connection)
 
1143
        try:
 
1144
            document = xml.dom.minidom.parseString(xmlstring)
 
1145
            
 
1146
            for if_tag in document.getElementsByTagName("interface"):
 
1147
                # Add annotation tags
 
1148
                for typ in ("method", "signal"):
 
1149
                    for tag in if_tag.getElementsByTagName(typ):
 
1150
                        annots = dict()
 
1151
                        for name, prop in (self.
 
1152
                                           _get_all_dbus_things(typ)):
 
1153
                            if (name == tag.getAttribute("name")
 
1154
                                and prop._dbus_interface
 
1155
                                == if_tag.getAttribute("name")):
 
1156
                                annots.update(getattr(
 
1157
                                    prop, "_dbus_annotations", {}))
 
1158
                        for name, value in annots.items():
 
1159
                            ann_tag = document.createElement(
 
1160
                                "annotation")
 
1161
                            ann_tag.setAttribute("name", name)
 
1162
                            ann_tag.setAttribute("value", value)
 
1163
                            tag.appendChild(ann_tag)
 
1164
                # Add interface annotation tags
 
1165
                for annotation, value in dict(
 
1166
                    itertools.chain.from_iterable(
 
1167
                        annotations().items()
 
1168
                        for name, annotations
 
1169
                        in self._get_all_dbus_things("interface")
 
1170
                        if name == if_tag.getAttribute("name")
 
1171
                        )).items():
 
1172
                    ann_tag = document.createElement("annotation")
 
1173
                    ann_tag.setAttribute("name", annotation)
 
1174
                    ann_tag.setAttribute("value", value)
 
1175
                    if_tag.appendChild(ann_tag)
 
1176
                # Fix argument name for the Introspect method itself
 
1177
                if (if_tag.getAttribute("name")
 
1178
                                == dbus.INTROSPECTABLE_IFACE):
 
1179
                    for cn in if_tag.getElementsByTagName("method"):
 
1180
                        if cn.getAttribute("name") == "Introspect":
 
1181
                            for arg in cn.getElementsByTagName("arg"):
 
1182
                                if (arg.getAttribute("direction")
 
1183
                                    == "out"):
 
1184
                                    arg.setAttribute("name",
 
1185
                                                     "xml_data")
 
1186
            xmlstring = document.toxml("utf-8")
 
1187
            document.unlink()
 
1188
        except (AttributeError, xml.dom.DOMException,
 
1189
                xml.parsers.expat.ExpatError) as error:
 
1190
            logger.error("Failed to override Introspection method",
 
1191
                         exc_info=error)
 
1192
        return xmlstring
 
1193
 
 
1194
 
 
1195
class DBusObjectWithProperties(DBusObjectWithAnnotations):
 
1196
    """A D-Bus object with properties.
 
1197
    
 
1198
    Classes inheriting from this can use the dbus_service_property
 
1199
    decorator to expose methods as D-Bus properties.  It exposes the
 
1200
    standard Get(), Set(), and GetAll() methods on the D-Bus.
 
1201
    """
 
1202
    
899
1203
    def _get_dbus_property(self, interface_name, property_name):
900
1204
        """Returns a bound method if one exists which is a D-Bus
901
1205
        property with the specified name and interface.
911
1215
        raise DBusPropertyNotFound("{}:{}.{}".format(
912
1216
            self.dbus_object_path, interface_name, property_name))
913
1217
    
 
1218
    @classmethod
 
1219
    def _get_all_interface_names(cls):
 
1220
        """Get a sequence of all interfaces supported by an object"""
 
1221
        return (name for name in set(getattr(getattr(x, attr),
 
1222
                                             "_dbus_interface", None)
 
1223
                                     for x in (inspect.getmro(cls))
 
1224
                                     for attr in dir(x))
 
1225
                if name is not None)
 
1226
    
914
1227
    @dbus.service.method(dbus.PROPERTIES_IFACE,
915
1228
                         in_signature="ss",
916
1229
                         out_signature="v")
986
1299
        
987
1300
        Inserts property tags and interface annotation tags.
988
1301
        """
989
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
990
 
                                                   connection)
 
1302
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
 
1303
                                                         object_path,
 
1304
                                                         connection)
991
1305
        try:
992
1306
            document = xml.dom.minidom.parseString(xmlstring)
993
1307
            
1006
1320
                            if prop._dbus_interface
1007
1321
                            == if_tag.getAttribute("name")):
1008
1322
                    if_tag.appendChild(tag)
1009
 
                # Add annotation tags
1010
 
                for typ in ("method", "signal", "property"):
1011
 
                    for tag in if_tag.getElementsByTagName(typ):
1012
 
                        annots = dict()
1013
 
                        for name, prop in (self.
1014
 
                                           _get_all_dbus_things(typ)):
1015
 
                            if (name == tag.getAttribute("name")
1016
 
                                and prop._dbus_interface
1017
 
                                == if_tag.getAttribute("name")):
1018
 
                                annots.update(getattr(
1019
 
                                    prop, "_dbus_annotations", {}))
1020
 
                        for name, value in annots.items():
1021
 
                            ann_tag = document.createElement(
1022
 
                                "annotation")
1023
 
                            ann_tag.setAttribute("name", name)
1024
 
                            ann_tag.setAttribute("value", value)
1025
 
                            tag.appendChild(ann_tag)
1026
 
                # Add interface annotation tags
1027
 
                for annotation, value in dict(
1028
 
                    itertools.chain.from_iterable(
1029
 
                        annotations().items()
1030
 
                        for name, annotations
1031
 
                        in self._get_all_dbus_things("interface")
1032
 
                        if name == if_tag.getAttribute("name")
1033
 
                        )).items():
1034
 
                    ann_tag = document.createElement("annotation")
1035
 
                    ann_tag.setAttribute("name", annotation)
1036
 
                    ann_tag.setAttribute("value", value)
1037
 
                    if_tag.appendChild(ann_tag)
 
1323
                # Add annotation tags for properties
 
1324
                for tag in if_tag.getElementsByTagName("property"):
 
1325
                    annots = dict()
 
1326
                    for name, prop in self._get_all_dbus_things(
 
1327
                            "property"):
 
1328
                        if (name == tag.getAttribute("name")
 
1329
                            and prop._dbus_interface
 
1330
                            == if_tag.getAttribute("name")):
 
1331
                            annots.update(getattr(
 
1332
                                prop, "_dbus_annotations", {}))
 
1333
                    for name, value in annots.items():
 
1334
                        ann_tag = document.createElement(
 
1335
                            "annotation")
 
1336
                        ann_tag.setAttribute("name", name)
 
1337
                        ann_tag.setAttribute("value", value)
 
1338
                        tag.appendChild(ann_tag)
1038
1339
                # Add the names to the return values for the
1039
1340
                # "org.freedesktop.DBus.Properties" methods
1040
1341
                if (if_tag.getAttribute("name")
1058
1359
                         exc_info=error)
1059
1360
        return xmlstring
1060
1361
 
 
1362
try:
 
1363
    dbus.OBJECT_MANAGER_IFACE
 
1364
except AttributeError:
 
1365
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
 
1366
 
 
1367
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
 
1368
    """A D-Bus object with an ObjectManager.
 
1369
    
 
1370
    Classes inheriting from this exposes the standard
 
1371
    GetManagedObjects call and the InterfacesAdded and
 
1372
    InterfacesRemoved signals on the standard
 
1373
    "org.freedesktop.DBus.ObjectManager" interface.
 
1374
    
 
1375
    Note: No signals are sent automatically; they must be sent
 
1376
    manually.
 
1377
    """
 
1378
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
 
1379
                         out_signature = "a{oa{sa{sv}}}")
 
1380
    def GetManagedObjects(self):
 
1381
        """This function must be overridden"""
 
1382
        raise NotImplementedError()
 
1383
    
 
1384
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
 
1385
                         signature = "oa{sa{sv}}")
 
1386
    def InterfacesAdded(self, object_path, interfaces_and_properties):
 
1387
        pass
 
1388
    
 
1389
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
 
1390
    def InterfacesRemoved(self, object_path, interfaces):
 
1391
        pass
 
1392
    
 
1393
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
 
1394
                         out_signature = "s",
 
1395
                         path_keyword = 'object_path',
 
1396
                         connection_keyword = 'connection')
 
1397
    def Introspect(self, object_path, connection):
 
1398
        """Overloading of standard D-Bus method.
 
1399
        
 
1400
        Override return argument name of GetManagedObjects to be
 
1401
        "objpath_interfaces_and_properties"
 
1402
        """
 
1403
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
 
1404
                                                         object_path,
 
1405
                                                         connection)
 
1406
        try:
 
1407
            document = xml.dom.minidom.parseString(xmlstring)
 
1408
            
 
1409
            for if_tag in document.getElementsByTagName("interface"):
 
1410
                # Fix argument name for the GetManagedObjects method
 
1411
                if (if_tag.getAttribute("name")
 
1412
                                == dbus.OBJECT_MANAGER_IFACE):
 
1413
                    for cn in if_tag.getElementsByTagName("method"):
 
1414
                        if (cn.getAttribute("name")
 
1415
                            == "GetManagedObjects"):
 
1416
                            for arg in cn.getElementsByTagName("arg"):
 
1417
                                if (arg.getAttribute("direction")
 
1418
                                    == "out"):
 
1419
                                    arg.setAttribute(
 
1420
                                        "name",
 
1421
                                        "objpath_interfaces"
 
1422
                                        "_and_properties")
 
1423
            xmlstring = document.toxml("utf-8")
 
1424
            document.unlink()
 
1425
        except (AttributeError, xml.dom.DOMException,
 
1426
                xml.parsers.expat.ExpatError) as error:
 
1427
            logger.error("Failed to override Introspection method",
 
1428
                         exc_info = error)
 
1429
        return xmlstring
1061
1430
 
1062
1431
def datetime_to_dbus(dt, variant_level=0):
1063
1432
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1154
1523
                        func1 and func2 to the "call_both" function
1155
1524
                        outside of its arguments"""
1156
1525
                        
 
1526
                        @functools.wraps(func2)
1157
1527
                        def call_both(*args, **kwargs):
1158
1528
                            """This function will emit two D-Bus
1159
1529
                            signals by calling func1 and func2"""
1160
1530
                            func1(*args, **kwargs)
1161
1531
                            func2(*args, **kwargs)
 
1532
                        # Make wrapper function look like a D-Bus signal
 
1533
                        for name, attr in inspect.getmembers(func2):
 
1534
                            if name.startswith("_dbus_"):
 
1535
                                setattr(call_both, name, attr)
1162
1536
                        
1163
1537
                        return call_both
1164
1538
                    # Create the "call_both" function and add it to
1376
1750
        if exitstatus >= 0:
1377
1751
            # Emit D-Bus signal
1378
1752
            self.CheckerCompleted(dbus.Int16(exitstatus),
1379
 
                                  dbus.Int64(0),
 
1753
                                  # This is specific to GNU libC
 
1754
                                  dbus.Int64(exitstatus << 8),
1380
1755
                                  dbus.String(command))
1381
1756
        else:
1382
1757
            # Emit D-Bus signal
1383
1758
            self.CheckerCompleted(dbus.Int16(-1),
1384
1759
                                  dbus.Int64(
1385
 
                                      self.last_checker_signal),
 
1760
                                      # This is specific to GNU libC
 
1761
                                      (exitstatus << 8)
 
1762
                                      | self.last_checker_signal),
1386
1763
                                  dbus.String(command))
1387
1764
        return ret
1388
1765
    
1465
1842
        self.checked_ok()
1466
1843
    
1467
1844
    # Enable - method
 
1845
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1468
1846
    @dbus.service.method(_interface)
1469
1847
    def Enable(self):
1470
1848
        "D-Bus method"
1471
1849
        self.enable()
1472
1850
    
1473
1851
    # StartChecker - method
 
1852
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1474
1853
    @dbus.service.method(_interface)
1475
1854
    def StartChecker(self):
1476
1855
        "D-Bus method"
1477
1856
        self.start_checker()
1478
1857
    
1479
1858
    # Disable - method
 
1859
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1480
1860
    @dbus.service.method(_interface)
1481
1861
    def Disable(self):
1482
1862
        "D-Bus method"
1483
1863
        self.disable()
1484
1864
    
1485
1865
    # StopChecker - method
 
1866
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1486
1867
    @dbus.service.method(_interface)
1487
1868
    def StopChecker(self):
1488
1869
        self.stop_checker()
1524
1905
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1525
1906
    
1526
1907
    # Name - property
 
1908
    @dbus_annotations(
 
1909
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1527
1910
    @dbus_service_property(_interface, signature="s", access="read")
1528
1911
    def Name_dbus_property(self):
1529
1912
        return dbus.String(self.name)
1530
1913
    
1531
1914
    # Fingerprint - property
 
1915
    @dbus_annotations(
 
1916
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1532
1917
    @dbus_service_property(_interface, signature="s", access="read")
1533
1918
    def Fingerprint_dbus_property(self):
1534
1919
        return dbus.String(self.fingerprint)
1543
1928
        self.host = str(value)
1544
1929
    
1545
1930
    # Created - property
 
1931
    @dbus_annotations(
 
1932
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1546
1933
    @dbus_service_property(_interface, signature="s", access="read")
1547
1934
    def Created_dbus_property(self):
1548
1935
        return datetime_to_dbus(self.created)
1663
2050
            self.stop_checker()
1664
2051
    
1665
2052
    # ObjectPath - property
 
2053
    @dbus_annotations(
 
2054
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
 
2055
         "org.freedesktop.DBus.Deprecated": "true"})
1666
2056
    @dbus_service_property(_interface, signature="o", access="read")
1667
2057
    def ObjectPath_dbus_property(self):
1668
2058
        return self.dbus_object_path # is already a dbus.ObjectPath
1669
2059
    
1670
2060
    # Secret = property
 
2061
    @dbus_annotations(
 
2062
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2063
         "invalidates"})
1671
2064
    @dbus_service_property(_interface,
1672
2065
                           signature="ay",
1673
2066
                           access="write",
1719
2112
            logger.debug("Pipe FD: %d",
1720
2113
                         self.server.child_pipe.fileno())
1721
2114
            
1722
 
            session = gnutls.connection.ClientSession(
1723
 
                self.request, gnutls.connection .X509Credentials())
1724
 
            
1725
 
            # Note: gnutls.connection.X509Credentials is really a
1726
 
            # generic GnuTLS certificate credentials object so long as
1727
 
            # no X.509 keys are added to it.  Therefore, we can use it
1728
 
            # here despite using OpenPGP certificates.
 
2115
            session = gnutls.ClientSession(self.request)
1729
2116
            
1730
2117
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1731
2118
            #                      "+AES-256-CBC", "+SHA1",
1735
2122
            priority = self.server.gnutls_priority
1736
2123
            if priority is None:
1737
2124
                priority = "NORMAL"
1738
 
            gnutls.library.functions.gnutls_priority_set_direct(
1739
 
                session._c_object, priority, None)
 
2125
            gnutls.priority_set_direct(session._c_object, priority,
 
2126
                                       None)
1740
2127
            
1741
2128
            # Start communication using the Mandos protocol
1742
2129
            # Get protocol number
1752
2139
            # Start GnuTLS connection
1753
2140
            try:
1754
2141
                session.handshake()
1755
 
            except gnutls.errors.GNUTLSError as error:
 
2142
            except gnutls.Error as error:
1756
2143
                logger.warning("Handshake failed: %s", error)
1757
2144
                # Do not run session.bye() here: the session is not
1758
2145
                # established.  Just abandon the request.
1764
2151
                try:
1765
2152
                    fpr = self.fingerprint(
1766
2153
                        self.peer_certificate(session))
1767
 
                except (TypeError,
1768
 
                        gnutls.errors.GNUTLSError) as error:
 
2154
                except (TypeError, gnutls.Error) as error:
1769
2155
                    logger.warning("Bad certificate: %s", error)
1770
2156
                    return
1771
2157
                logger.debug("Fingerprint: %s", fpr)
1833
2219
                while sent_size < len(client.secret):
1834
2220
                    try:
1835
2221
                        sent = session.send(client.secret[sent_size:])
1836
 
                    except gnutls.errors.GNUTLSError as error:
 
2222
                    except gnutls.Error as error:
1837
2223
                        logger.warning("gnutls send failed",
1838
2224
                                       exc_info=error)
1839
2225
                        return
1854
2240
                    client.approvals_pending -= 1
1855
2241
                try:
1856
2242
                    session.bye()
1857
 
                except gnutls.errors.GNUTLSError as error:
 
2243
                except gnutls.Error as error:
1858
2244
                    logger.warning("GnuTLS bye failed",
1859
2245
                                   exc_info=error)
1860
2246
    
1862
2248
    def peer_certificate(session):
1863
2249
        "Return the peer's OpenPGP certificate as a bytestring"
1864
2250
        # If not an OpenPGP certificate...
1865
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1866
 
                session._c_object)
1867
 
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1868
 
            # ...do the normal thing
1869
 
            return session.peer_certificate
 
2251
        if (gnutls.certificate_type_get(session._c_object)
 
2252
            != gnutls.CRT_OPENPGP):
 
2253
            # ...return invalid data
 
2254
            return b""
1870
2255
        list_size = ctypes.c_uint(1)
1871
 
        cert_list = (gnutls.library.functions
1872
 
                     .gnutls_certificate_get_peers
 
2256
        cert_list = (gnutls.certificate_get_peers
1873
2257
                     (session._c_object, ctypes.byref(list_size)))
1874
2258
        if not bool(cert_list) and list_size.value != 0:
1875
 
            raise gnutls.errors.GNUTLSError("error getting peer"
1876
 
                                            " certificate")
 
2259
            raise gnutls.Error("error getting peer certificate")
1877
2260
        if list_size.value == 0:
1878
2261
            return None
1879
2262
        cert = cert_list[0]
1883
2266
    def fingerprint(openpgp):
1884
2267
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1885
2268
        # New GnuTLS "datum" with the OpenPGP public key
1886
 
        datum = gnutls.library.types.gnutls_datum_t(
 
2269
        datum = gnutls.datum_t(
1887
2270
            ctypes.cast(ctypes.c_char_p(openpgp),
1888
2271
                        ctypes.POINTER(ctypes.c_ubyte)),
1889
2272
            ctypes.c_uint(len(openpgp)))
1890
2273
        # New empty GnuTLS certificate
1891
 
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1892
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1893
 
            ctypes.byref(crt))
 
2274
        crt = gnutls.openpgp_crt_t()
 
2275
        gnutls.openpgp_crt_init(ctypes.byref(crt))
1894
2276
        # Import the OpenPGP public key into the certificate
1895
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1896
 
            crt, ctypes.byref(datum),
1897
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
2277
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
 
2278
                                  gnutls.OPENPGP_FMT_RAW)
1898
2279
        # Verify the self signature in the key
1899
2280
        crtverify = ctypes.c_uint()
1900
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1901
 
            crt, 0, ctypes.byref(crtverify))
 
2281
        gnutls.openpgp_crt_verify_self(crt, 0,
 
2282
                                       ctypes.byref(crtverify))
1902
2283
        if crtverify.value != 0:
1903
 
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1904
 
            raise gnutls.errors.CertificateSecurityError(
1905
 
                "Verify failed")
 
2284
            gnutls.openpgp_crt_deinit(crt)
 
2285
            raise gnutls.CertificateSecurityError("Verify failed")
1906
2286
        # New buffer for the fingerprint
1907
2287
        buf = ctypes.create_string_buffer(20)
1908
2288
        buf_len = ctypes.c_size_t()
1909
2289
        # Get the fingerprint from the certificate into the buffer
1910
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1911
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
2290
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
2291
                                           ctypes.byref(buf_len))
1912
2292
        # Deinit the certificate
1913
 
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
2293
        gnutls.openpgp_crt_deinit(crt)
1914
2294
        # Convert the buffer to a Python bytestring
1915
2295
        fpr = ctypes.string_at(buf, buf_len.value)
1916
2296
        # Convert the bytestring to hexadecimal notation
2397
2777
                        "debug": "False",
2398
2778
                        "priority":
2399
2779
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2400
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2780
                        ":+SIGN-DSA-SHA256",
2401
2781
                        "servicename": "Mandos",
2402
2782
                        "use_dbus": "True",
2403
2783
                        "use_ipv6": "True",
2542
2922
        
2543
2923
        # "Use a log level over 10 to enable all debugging options."
2544
2924
        # - GnuTLS manual
2545
 
        gnutls.library.functions.gnutls_global_set_log_level(11)
 
2925
        gnutls.global_set_log_level(11)
2546
2926
        
2547
 
        @gnutls.library.types.gnutls_log_func
 
2927
        @gnutls.log_func
2548
2928
        def debug_gnutls(level, string):
2549
2929
            logger.debug("GnuTLS: %s", string[:-1])
2550
2930
        
2551
 
        gnutls.library.functions.gnutls_global_set_log_function(
2552
 
            debug_gnutls)
 
2931
        gnutls.global_set_log_function(debug_gnutls)
2553
2932
        
2554
2933
        # Redirect stdin so all checkers get /dev/null
2555
2934
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2734
3113
        
2735
3114
        @alternate_dbus_interfaces(
2736
3115
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2737
 
        class MandosDBusService(DBusObjectWithProperties):
 
3116
        class MandosDBusService(DBusObjectWithObjectManager):
2738
3117
            """A D-Bus proxy object"""
2739
3118
            
2740
3119
            def __init__(self):
2742
3121
            
2743
3122
            _interface = "se.recompile.Mandos"
2744
3123
            
2745
 
            @dbus_interface_annotations(_interface)
2746
 
            def _foo(self):
2747
 
                return {
2748
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2749
 
                    "false" }
2750
 
            
2751
3124
            @dbus.service.signal(_interface, signature="o")
2752
3125
            def ClientAdded(self, objpath):
2753
3126
                "D-Bus signal"
2758
3131
                "D-Bus signal"
2759
3132
                pass
2760
3133
            
 
3134
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3135
                               "true"})
2761
3136
            @dbus.service.signal(_interface, signature="os")
2762
3137
            def ClientRemoved(self, objpath, name):
2763
3138
                "D-Bus signal"
2764
3139
                pass
2765
3140
            
 
3141
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3142
                               "true"})
2766
3143
            @dbus.service.method(_interface, out_signature="ao")
2767
3144
            def GetAllClients(self):
2768
3145
                "D-Bus method"
2769
3146
                return dbus.Array(c.dbus_object_path for c in
2770
3147
                                  tcp_server.clients.itervalues())
2771
3148
            
 
3149
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3150
                               "true"})
2772
3151
            @dbus.service.method(_interface,
2773
3152
                                 out_signature="a{oa{sv}}")
2774
3153
            def GetAllClientsWithProperties(self):
2775
3154
                "D-Bus method"
2776
3155
                return dbus.Dictionary(
2777
 
                    { c.dbus_object_path: c.GetAll("")
 
3156
                    { c.dbus_object_path: c.GetAll(
 
3157
                        "se.recompile.Mandos.Client")
2778
3158
                      for c in tcp_server.clients.itervalues() },
2779
3159
                    signature="oa{sv}")
2780
3160
            
2785
3165
                    if c.dbus_object_path == object_path:
2786
3166
                        del tcp_server.clients[c.name]
2787
3167
                        c.remove_from_connection()
2788
 
                        # Don't signal anything except ClientRemoved
 
3168
                        # Don't signal the disabling
2789
3169
                        c.disable(quiet=True)
2790
 
                        # Emit D-Bus signal
2791
 
                        self.ClientRemoved(object_path, c.name)
 
3170
                        # Emit D-Bus signal for removal
 
3171
                        self.client_removed_signal(c)
2792
3172
                        return
2793
3173
                raise KeyError(object_path)
2794
3174
            
2795
3175
            del _interface
 
3176
            
 
3177
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
 
3178
                                 out_signature = "a{oa{sa{sv}}}")
 
3179
            def GetManagedObjects(self):
 
3180
                """D-Bus method"""
 
3181
                return dbus.Dictionary(
 
3182
                    { client.dbus_object_path:
 
3183
                      dbus.Dictionary(
 
3184
                          { interface: client.GetAll(interface)
 
3185
                            for interface in
 
3186
                                 client._get_all_interface_names()})
 
3187
                      for client in tcp_server.clients.values()})
 
3188
            
 
3189
            def client_added_signal(self, client):
 
3190
                """Send the new standard signal and the old signal"""
 
3191
                if use_dbus:
 
3192
                    # New standard signal
 
3193
                    self.InterfacesAdded(
 
3194
                        client.dbus_object_path,
 
3195
                        dbus.Dictionary(
 
3196
                            { interface: client.GetAll(interface)
 
3197
                              for interface in
 
3198
                              client._get_all_interface_names()}))
 
3199
                    # Old signal
 
3200
                    self.ClientAdded(client.dbus_object_path)
 
3201
            
 
3202
            def client_removed_signal(self, client):
 
3203
                """Send the new standard signal and the old signal"""
 
3204
                if use_dbus:
 
3205
                    # New standard signal
 
3206
                    self.InterfacesRemoved(
 
3207
                        client.dbus_object_path,
 
3208
                        client._get_all_interface_names())
 
3209
                    # Old signal
 
3210
                    self.ClientRemoved(client.dbus_object_path,
 
3211
                                       client.name)
2796
3212
        
2797
3213
        mandos_dbus_service = MandosDBusService()
2798
3214
    
2863
3279
            name, client = tcp_server.clients.popitem()
2864
3280
            if use_dbus:
2865
3281
                client.remove_from_connection()
2866
 
            # Don't signal anything except ClientRemoved
 
3282
            # Don't signal the disabling
2867
3283
            client.disable(quiet=True)
 
3284
            # Emit D-Bus signal for removal
2868
3285
            if use_dbus:
2869
 
                # Emit D-Bus signal
2870
 
                mandos_dbus_service.ClientRemoved(
2871
 
                    client.dbus_object_path, client.name)
 
3286
                mandos_dbus_service.client_removed_signal(client)
2872
3287
        client_settings.clear()
2873
3288
    
2874
3289
    atexit.register(cleanup)
2875
3290
    
2876
3291
    for client in tcp_server.clients.itervalues():
2877
3292
        if use_dbus:
2878
 
            # Emit D-Bus signal
2879
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
3293
            # Emit D-Bus signal for adding
 
3294
            mandos_dbus_service.client_added_signal(client)
2880
3295
        # Need to initiate checking of clients
2881
3296
        if client.enabled:
2882
3297
            client.init_checker()