/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: 2015-07-09 20:36:29 UTC
  • Revision ID: teddy@recompile.se-20150709203629-439gfk6812u1azp3
Rename the "client-dhparams.pem" file to simply "dhparams.pem".

* debian/mandos-client.postinst: Rename the "client-dhparams.pem" file
                                 to "dhparams.pem".
* initramfs-tools-hook: - '' -
* plugins.d/mandos-client.c (main): - '' -

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
47
53
try:
48
54
    import ConfigParser as configparser
49
55
except ImportError:
98
104
if sys.version_info.major == 2:
99
105
    str = unicode
100
106
 
101
 
version = "1.7.1"
 
107
version = "1.6.9"
102
108
stored_state_file = "clients.pickle"
103
109
 
104
110
logger = logging.getLogger()
389
395
                    logger.error(bad_states[state] + ": %r", error)
390
396
            self.cleanup()
391
397
        elif state == avahi.SERVER_RUNNING:
392
 
            try:
393
 
                self.add()
394
 
            except dbus.exceptions.DBusException as error:
395
 
                if (error.get_dbus_name()
396
 
                    == "org.freedesktop.Avahi.CollisionError"):
397
 
                    logger.info("Local Zeroconf service name"
398
 
                                " collision.")
399
 
                    return self.rename(remove=False)
400
 
                else:
401
 
                    logger.critical("D-Bus Exception", exc_info=error)
402
 
                    self.cleanup()
403
 
                    os._exit(1)
 
398
            self.add()
404
399
        else:
405
400
            if error is None:
406
401
                logger.debug("Unknown state: %r", state)
429
424
            .format(self.name)))
430
425
        return ret
431
426
 
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
 
 
670
427
def call_pipe(connection,       # : multiprocessing.Connection
671
428
              func, *args, **kwargs):
672
429
    """This function is meant to be called by multiprocessing.Process
1074
831
                           access="r")
1075
832
    def Property_dbus_property(self):
1076
833
        return dbus.Boolean(False)
1077
 
    
1078
 
    See also the DBusObjectWithAnnotations class.
1079
834
    """
1080
835
    
1081
836
    def decorator(func):
1103
858
    pass
1104
859
 
1105
860
 
1106
 
class DBusObjectWithAnnotations(dbus.service.Object):
1107
 
    """A D-Bus object with annotations.
 
861
class DBusObjectWithProperties(dbus.service.Object):
 
862
    """A D-Bus object with properties.
1108
863
    
1109
 
    Classes inheriting from this can use the dbus_annotations
1110
 
    decorator to add annotations to methods or signals.
 
864
    Classes inheriting from this can use the dbus_service_property
 
865
    decorator to expose methods as D-Bus properties.  It exposes the
 
866
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1111
867
    """
1112
868
    
1113
869
    @staticmethod
1129
885
                for name, athing in
1130
886
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1131
887
    
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
 
    
1203
888
    def _get_dbus_property(self, interface_name, property_name):
1204
889
        """Returns a bound method if one exists which is a D-Bus
1205
890
        property with the specified name and interface.
1215
900
        raise DBusPropertyNotFound("{}:{}.{}".format(
1216
901
            self.dbus_object_path, interface_name, property_name))
1217
902
    
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
 
    
1227
903
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1228
904
                         in_signature="ss",
1229
905
                         out_signature="v")
1299
975
        
1300
976
        Inserts property tags and interface annotation tags.
1301
977
        """
1302
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1303
 
                                                         object_path,
1304
 
                                                         connection)
 
978
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
979
                                                   connection)
1305
980
        try:
1306
981
            document = xml.dom.minidom.parseString(xmlstring)
1307
982
            
1320
995
                            if prop._dbus_interface
1321
996
                            == if_tag.getAttribute("name")):
1322
997
                    if_tag.appendChild(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)
 
998
                # Add annotation tags
 
999
                for typ in ("method", "signal", "property"):
 
1000
                    for tag in if_tag.getElementsByTagName(typ):
 
1001
                        annots = dict()
 
1002
                        for name, prop in (self.
 
1003
                                           _get_all_dbus_things(typ)):
 
1004
                            if (name == tag.getAttribute("name")
 
1005
                                and prop._dbus_interface
 
1006
                                == if_tag.getAttribute("name")):
 
1007
                                annots.update(getattr(
 
1008
                                    prop, "_dbus_annotations", {}))
 
1009
                        for name, value in annots.items():
 
1010
                            ann_tag = document.createElement(
 
1011
                                "annotation")
 
1012
                            ann_tag.setAttribute("name", name)
 
1013
                            ann_tag.setAttribute("value", value)
 
1014
                            tag.appendChild(ann_tag)
 
1015
                # Add interface annotation tags
 
1016
                for annotation, value in dict(
 
1017
                    itertools.chain.from_iterable(
 
1018
                        annotations().items()
 
1019
                        for name, annotations
 
1020
                        in self._get_all_dbus_things("interface")
 
1021
                        if name == if_tag.getAttribute("name")
 
1022
                        )).items():
 
1023
                    ann_tag = document.createElement("annotation")
 
1024
                    ann_tag.setAttribute("name", annotation)
 
1025
                    ann_tag.setAttribute("value", value)
 
1026
                    if_tag.appendChild(ann_tag)
1339
1027
                # Add the names to the return values for the
1340
1028
                # "org.freedesktop.DBus.Properties" methods
1341
1029
                if (if_tag.getAttribute("name")
1359
1047
                         exc_info=error)
1360
1048
        return xmlstring
1361
1049
 
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
1430
1050
 
1431
1051
def datetime_to_dbus(dt, variant_level=0):
1432
1052
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1523
1143
                        func1 and func2 to the "call_both" function
1524
1144
                        outside of its arguments"""
1525
1145
                        
1526
 
                        @functools.wraps(func2)
1527
1146
                        def call_both(*args, **kwargs):
1528
1147
                            """This function will emit two D-Bus
1529
1148
                            signals by calling func1 and func2"""
1530
1149
                            func1(*args, **kwargs)
1531
1150
                            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)
1536
1151
                        
1537
1152
                        return call_both
1538
1153
                    # Create the "call_both" function and add it to
1750
1365
        if exitstatus >= 0:
1751
1366
            # Emit D-Bus signal
1752
1367
            self.CheckerCompleted(dbus.Int16(exitstatus),
1753
 
                                  # This is specific to GNU libC
1754
 
                                  dbus.Int64(exitstatus << 8),
 
1368
                                  dbus.Int64(0),
1755
1369
                                  dbus.String(command))
1756
1370
        else:
1757
1371
            # Emit D-Bus signal
1758
1372
            self.CheckerCompleted(dbus.Int16(-1),
1759
1373
                                  dbus.Int64(
1760
 
                                      # This is specific to GNU libC
1761
 
                                      (exitstatus << 8)
1762
 
                                      | self.last_checker_signal),
 
1374
                                      self.last_checker_signal),
1763
1375
                                  dbus.String(command))
1764
1376
        return ret
1765
1377
    
1842
1454
        self.checked_ok()
1843
1455
    
1844
1456
    # Enable - method
1845
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1846
1457
    @dbus.service.method(_interface)
1847
1458
    def Enable(self):
1848
1459
        "D-Bus method"
1849
1460
        self.enable()
1850
1461
    
1851
1462
    # StartChecker - method
1852
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1853
1463
    @dbus.service.method(_interface)
1854
1464
    def StartChecker(self):
1855
1465
        "D-Bus method"
1856
1466
        self.start_checker()
1857
1467
    
1858
1468
    # Disable - method
1859
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1860
1469
    @dbus.service.method(_interface)
1861
1470
    def Disable(self):
1862
1471
        "D-Bus method"
1863
1472
        self.disable()
1864
1473
    
1865
1474
    # StopChecker - method
1866
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1867
1475
    @dbus.service.method(_interface)
1868
1476
    def StopChecker(self):
1869
1477
        self.stop_checker()
1905
1513
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1906
1514
    
1907
1515
    # Name - property
1908
 
    @dbus_annotations(
1909
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1910
1516
    @dbus_service_property(_interface, signature="s", access="read")
1911
1517
    def Name_dbus_property(self):
1912
1518
        return dbus.String(self.name)
1913
1519
    
1914
1520
    # Fingerprint - property
1915
 
    @dbus_annotations(
1916
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1917
1521
    @dbus_service_property(_interface, signature="s", access="read")
1918
1522
    def Fingerprint_dbus_property(self):
1919
1523
        return dbus.String(self.fingerprint)
1928
1532
        self.host = str(value)
1929
1533
    
1930
1534
    # Created - property
1931
 
    @dbus_annotations(
1932
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1933
1535
    @dbus_service_property(_interface, signature="s", access="read")
1934
1536
    def Created_dbus_property(self):
1935
1537
        return datetime_to_dbus(self.created)
2050
1652
            self.stop_checker()
2051
1653
    
2052
1654
    # ObjectPath - property
2053
 
    @dbus_annotations(
2054
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2055
 
         "org.freedesktop.DBus.Deprecated": "true"})
2056
1655
    @dbus_service_property(_interface, signature="o", access="read")
2057
1656
    def ObjectPath_dbus_property(self):
2058
1657
        return self.dbus_object_path # is already a dbus.ObjectPath
2059
1658
    
2060
1659
    # Secret = property
2061
 
    @dbus_annotations(
2062
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2063
 
         "invalidates"})
2064
1660
    @dbus_service_property(_interface,
2065
1661
                           signature="ay",
2066
1662
                           access="write",
2112
1708
            logger.debug("Pipe FD: %d",
2113
1709
                         self.server.child_pipe.fileno())
2114
1710
            
2115
 
            session = gnutls.ClientSession(self.request)
 
1711
            session = gnutls.connection.ClientSession(
 
1712
                self.request, gnutls.connection .X509Credentials())
 
1713
            
 
1714
            # Note: gnutls.connection.X509Credentials is really a
 
1715
            # generic GnuTLS certificate credentials object so long as
 
1716
            # no X.509 keys are added to it.  Therefore, we can use it
 
1717
            # here despite using OpenPGP certificates.
2116
1718
            
2117
1719
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
2118
1720
            #                      "+AES-256-CBC", "+SHA1",
2122
1724
            priority = self.server.gnutls_priority
2123
1725
            if priority is None:
2124
1726
                priority = "NORMAL"
2125
 
            gnutls.priority_set_direct(session._c_object, priority,
2126
 
                                       None)
 
1727
            gnutls.library.functions.gnutls_priority_set_direct(
 
1728
                session._c_object, priority, None)
2127
1729
            
2128
1730
            # Start communication using the Mandos protocol
2129
1731
            # Get protocol number
2139
1741
            # Start GnuTLS connection
2140
1742
            try:
2141
1743
                session.handshake()
2142
 
            except gnutls.Error as error:
 
1744
            except gnutls.errors.GNUTLSError as error:
2143
1745
                logger.warning("Handshake failed: %s", error)
2144
1746
                # Do not run session.bye() here: the session is not
2145
1747
                # established.  Just abandon the request.
2151
1753
                try:
2152
1754
                    fpr = self.fingerprint(
2153
1755
                        self.peer_certificate(session))
2154
 
                except (TypeError, gnutls.Error) as error:
 
1756
                except (TypeError,
 
1757
                        gnutls.errors.GNUTLSError) as error:
2155
1758
                    logger.warning("Bad certificate: %s", error)
2156
1759
                    return
2157
1760
                logger.debug("Fingerprint: %s", fpr)
2219
1822
                while sent_size < len(client.secret):
2220
1823
                    try:
2221
1824
                        sent = session.send(client.secret[sent_size:])
2222
 
                    except gnutls.Error as error:
 
1825
                    except gnutls.errors.GNUTLSError as error:
2223
1826
                        logger.warning("gnutls send failed",
2224
1827
                                       exc_info=error)
2225
1828
                        return
2240
1843
                    client.approvals_pending -= 1
2241
1844
                try:
2242
1845
                    session.bye()
2243
 
                except gnutls.Error as error:
 
1846
                except gnutls.errors.GNUTLSError as error:
2244
1847
                    logger.warning("GnuTLS bye failed",
2245
1848
                                   exc_info=error)
2246
1849
    
2248
1851
    def peer_certificate(session):
2249
1852
        "Return the peer's OpenPGP certificate as a bytestring"
2250
1853
        # If not an OpenPGP certificate...
2251
 
        if (gnutls.certificate_type_get(session._c_object)
2252
 
            != gnutls.CRT_OPENPGP):
2253
 
            # ...return invalid data
2254
 
            return b""
 
1854
        if (gnutls.library.functions.gnutls_certificate_type_get(
 
1855
                session._c_object)
 
1856
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1857
            # ...do the normal thing
 
1858
            return session.peer_certificate
2255
1859
        list_size = ctypes.c_uint(1)
2256
 
        cert_list = (gnutls.certificate_get_peers
 
1860
        cert_list = (gnutls.library.functions
 
1861
                     .gnutls_certificate_get_peers
2257
1862
                     (session._c_object, ctypes.byref(list_size)))
2258
1863
        if not bool(cert_list) and list_size.value != 0:
2259
 
            raise gnutls.Error("error getting peer certificate")
 
1864
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1865
                                            " certificate")
2260
1866
        if list_size.value == 0:
2261
1867
            return None
2262
1868
        cert = cert_list[0]
2266
1872
    def fingerprint(openpgp):
2267
1873
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2268
1874
        # New GnuTLS "datum" with the OpenPGP public key
2269
 
        datum = gnutls.datum_t(
 
1875
        datum = gnutls.library.types.gnutls_datum_t(
2270
1876
            ctypes.cast(ctypes.c_char_p(openpgp),
2271
1877
                        ctypes.POINTER(ctypes.c_ubyte)),
2272
1878
            ctypes.c_uint(len(openpgp)))
2273
1879
        # New empty GnuTLS certificate
2274
 
        crt = gnutls.openpgp_crt_t()
2275
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1880
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1881
        gnutls.library.functions.gnutls_openpgp_crt_init(
 
1882
            ctypes.byref(crt))
2276
1883
        # Import the OpenPGP public key into the certificate
2277
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2278
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1884
        gnutls.library.functions.gnutls_openpgp_crt_import(
 
1885
            crt, ctypes.byref(datum),
 
1886
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
2279
1887
        # Verify the self signature in the key
2280
1888
        crtverify = ctypes.c_uint()
2281
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2282
 
                                       ctypes.byref(crtverify))
 
1889
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
 
1890
            crt, 0, ctypes.byref(crtverify))
2283
1891
        if crtverify.value != 0:
2284
 
            gnutls.openpgp_crt_deinit(crt)
2285
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1892
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1893
            raise gnutls.errors.CertificateSecurityError(
 
1894
                "Verify failed")
2286
1895
        # New buffer for the fingerprint
2287
1896
        buf = ctypes.create_string_buffer(20)
2288
1897
        buf_len = ctypes.c_size_t()
2289
1898
        # Get the fingerprint from the certificate into the buffer
2290
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2291
 
                                           ctypes.byref(buf_len))
 
1899
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
 
1900
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
2292
1901
        # Deinit the certificate
2293
 
        gnutls.openpgp_crt_deinit(crt)
 
1902
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2294
1903
        # Convert the buffer to a Python bytestring
2295
1904
        fpr = ctypes.string_at(buf, buf_len.value)
2296
1905
        # Convert the bytestring to hexadecimal notation
2777
2386
                        "debug": "False",
2778
2387
                        "priority":
2779
2388
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2780
 
                        ":+SIGN-DSA-SHA256",
 
2389
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2781
2390
                        "servicename": "Mandos",
2782
2391
                        "use_dbus": "True",
2783
2392
                        "use_ipv6": "True",
2922
2531
        
2923
2532
        # "Use a log level over 10 to enable all debugging options."
2924
2533
        # - GnuTLS manual
2925
 
        gnutls.global_set_log_level(11)
 
2534
        gnutls.library.functions.gnutls_global_set_log_level(11)
2926
2535
        
2927
 
        @gnutls.log_func
 
2536
        @gnutls.library.types.gnutls_log_func
2928
2537
        def debug_gnutls(level, string):
2929
2538
            logger.debug("GnuTLS: %s", string[:-1])
2930
2539
        
2931
 
        gnutls.global_set_log_function(debug_gnutls)
 
2540
        gnutls.library.functions.gnutls_global_set_log_function(
 
2541
            debug_gnutls)
2932
2542
        
2933
2543
        # Redirect stdin so all checkers get /dev/null
2934
2544
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
3113
2723
        
3114
2724
        @alternate_dbus_interfaces(
3115
2725
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
3116
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2726
        class MandosDBusService(DBusObjectWithProperties):
3117
2727
            """A D-Bus proxy object"""
3118
2728
            
3119
2729
            def __init__(self):
3121
2731
            
3122
2732
            _interface = "se.recompile.Mandos"
3123
2733
            
 
2734
            @dbus_interface_annotations(_interface)
 
2735
            def _foo(self):
 
2736
                return {
 
2737
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2738
                    "false" }
 
2739
            
3124
2740
            @dbus.service.signal(_interface, signature="o")
3125
2741
            def ClientAdded(self, objpath):
3126
2742
                "D-Bus signal"
3131
2747
                "D-Bus signal"
3132
2748
                pass
3133
2749
            
3134
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3135
 
                               "true"})
3136
2750
            @dbus.service.signal(_interface, signature="os")
3137
2751
            def ClientRemoved(self, objpath, name):
3138
2752
                "D-Bus signal"
3139
2753
                pass
3140
2754
            
3141
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3142
 
                               "true"})
3143
2755
            @dbus.service.method(_interface, out_signature="ao")
3144
2756
            def GetAllClients(self):
3145
2757
                "D-Bus method"
3146
2758
                return dbus.Array(c.dbus_object_path for c in
3147
2759
                                  tcp_server.clients.itervalues())
3148
2760
            
3149
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3150
 
                               "true"})
3151
2761
            @dbus.service.method(_interface,
3152
2762
                                 out_signature="a{oa{sv}}")
3153
2763
            def GetAllClientsWithProperties(self):
3154
2764
                "D-Bus method"
3155
2765
                return dbus.Dictionary(
3156
 
                    { c.dbus_object_path: c.GetAll(
3157
 
                        "se.recompile.Mandos.Client")
 
2766
                    { c.dbus_object_path: c.GetAll("")
3158
2767
                      for c in tcp_server.clients.itervalues() },
3159
2768
                    signature="oa{sv}")
3160
2769
            
3165
2774
                    if c.dbus_object_path == object_path:
3166
2775
                        del tcp_server.clients[c.name]
3167
2776
                        c.remove_from_connection()
3168
 
                        # Don't signal the disabling
 
2777
                        # Don't signal anything except ClientRemoved
3169
2778
                        c.disable(quiet=True)
3170
 
                        # Emit D-Bus signal for removal
3171
 
                        self.client_removed_signal(c)
 
2779
                        # Emit D-Bus signal
 
2780
                        self.ClientRemoved(object_path, c.name)
3172
2781
                        return
3173
2782
                raise KeyError(object_path)
3174
2783
            
3175
2784
            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)
3212
2785
        
3213
2786
        mandos_dbus_service = MandosDBusService()
3214
2787
    
3279
2852
            name, client = tcp_server.clients.popitem()
3280
2853
            if use_dbus:
3281
2854
                client.remove_from_connection()
3282
 
            # Don't signal the disabling
 
2855
            # Don't signal anything except ClientRemoved
3283
2856
            client.disable(quiet=True)
3284
 
            # Emit D-Bus signal for removal
3285
2857
            if use_dbus:
3286
 
                mandos_dbus_service.client_removed_signal(client)
 
2858
                # Emit D-Bus signal
 
2859
                mandos_dbus_service.ClientRemoved(
 
2860
                    client.dbus_object_path, client.name)
3287
2861
        client_settings.clear()
3288
2862
    
3289
2863
    atexit.register(cleanup)
3290
2864
    
3291
2865
    for client in tcp_server.clients.itervalues():
3292
2866
        if use_dbus:
3293
 
            # Emit D-Bus signal for adding
3294
 
            mandos_dbus_service.client_added_signal(client)
 
2867
            # Emit D-Bus signal
 
2868
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3295
2869
        # Need to initiate checking of clients
3296
2870
        if client.enabled:
3297
2871
            client.init_checker()