/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()
395
389
                    logger.error(bad_states[state] + ": %r", error)
396
390
            self.cleanup()
397
391
        elif state == avahi.SERVER_RUNNING:
398
 
            self.add()
 
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)
399
404
        else:
400
405
            if error is None:
401
406
                logger.debug("Unknown state: %r", state)
424
429
            .format(self.name)))
425
430
        return ret
426
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
 
 
670
def call_pipe(connection,       # : multiprocessing.Connection
 
671
              func, *args, **kwargs):
 
672
    """This function is meant to be called by multiprocessing.Process
 
673
    
 
674
    This function runs func(*args, **kwargs), and writes the resulting
 
675
    return value on the provided multiprocessing.Connection.
 
676
    """
 
677
    connection.send(func(*args, **kwargs))
 
678
    connection.close()
427
679
 
428
680
class Client(object):
429
681
    """A representation of a client host served by this server.
456
708
    last_checker_status: integer between 0 and 255 reflecting exit
457
709
                         status of last checker. -1 reflects crashed
458
710
                         checker, -2 means no checker completed yet.
 
711
    last_checker_signal: The signal which killed the last checker, if
 
712
                         last_checker_status is -1
459
713
    last_enabled: datetime.datetime(); (UTC) or None
460
714
    name:       string; from the config file, used in log messages and
461
715
                        D-Bus identifiers
635
889
        # Also start a new checker *right now*.
636
890
        self.start_checker()
637
891
    
638
 
    def checker_callback(self, pid, condition, command):
 
892
    def checker_callback(self, source, condition, connection,
 
893
                         command):
639
894
        """The checker has completed, so take appropriate actions."""
640
895
        self.checker_callback_tag = None
641
896
        self.checker = None
642
 
        if os.WIFEXITED(condition):
643
 
            self.last_checker_status = os.WEXITSTATUS(condition)
 
897
        # Read return code from connection (see call_pipe)
 
898
        returncode = connection.recv()
 
899
        connection.close()
 
900
        
 
901
        if returncode >= 0:
 
902
            self.last_checker_status = returncode
 
903
            self.last_checker_signal = None
644
904
            if self.last_checker_status == 0:
645
905
                logger.info("Checker for %(name)s succeeded",
646
906
                            vars(self))
649
909
                logger.info("Checker for %(name)s failed", vars(self))
650
910
        else:
651
911
            self.last_checker_status = -1
 
912
            self.last_checker_signal = -returncode
652
913
            logger.warning("Checker for %(name)s crashed?",
653
914
                           vars(self))
 
915
        return False
654
916
    
655
917
    def checked_ok(self):
656
918
        """Assert that the client has been seen, alive and well."""
657
919
        self.last_checked_ok = datetime.datetime.utcnow()
658
920
        self.last_checker_status = 0
 
921
        self.last_checker_signal = None
659
922
        self.bump_timeout()
660
923
    
661
924
    def bump_timeout(self, timeout=None):
687
950
        # than 'timeout' for the client to be disabled, which is as it
688
951
        # should be.
689
952
        
690
 
        # If a checker exists, make sure it is not a zombie
691
 
        try:
692
 
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
693
 
        except AttributeError:
694
 
            pass
695
 
        except OSError as error:
696
 
            if error.errno != errno.ECHILD:
697
 
                raise
698
 
        else:
699
 
            if pid:
700
 
                logger.warning("Checker was a zombie")
701
 
                gobject.source_remove(self.checker_callback_tag)
702
 
                self.checker_callback(pid, status,
703
 
                                      self.current_checker_command)
 
953
        if self.checker is not None and not self.checker.is_alive():
 
954
            logger.warning("Checker was not alive; joining")
 
955
            self.checker.join()
 
956
            self.checker = None
704
957
        # Start a new checker if needed
705
958
        if self.checker is None:
706
959
            # Escape attributes for the shell
715
968
                             exc_info=error)
716
969
                return True     # Try again later
717
970
            self.current_checker_command = command
718
 
            try:
719
 
                logger.info("Starting checker %r for %s", command,
720
 
                            self.name)
721
 
                # We don't need to redirect stdout and stderr, since
722
 
                # in normal mode, that is already done by daemon(),
723
 
                # and in debug mode we don't want to.  (Stdin is
724
 
                # always replaced by /dev/null.)
725
 
                # The exception is when not debugging but nevertheless
726
 
                # running in the foreground; use the previously
727
 
                # created wnull.
728
 
                popen_args = {}
729
 
                if (not self.server_settings["debug"]
730
 
                    and self.server_settings["foreground"]):
731
 
                    popen_args.update({"stdout": wnull,
732
 
                                       "stderr": wnull })
733
 
                self.checker = subprocess.Popen(command,
734
 
                                                close_fds=True,
735
 
                                                shell=True,
736
 
                                                cwd="/",
737
 
                                                **popen_args)
738
 
            except OSError as error:
739
 
                logger.error("Failed to start subprocess",
740
 
                             exc_info=error)
741
 
                return True
742
 
            self.checker_callback_tag = gobject.child_watch_add(
743
 
                self.checker.pid, self.checker_callback, data=command)
744
 
            # The checker may have completed before the gobject
745
 
            # watch was added.  Check for this.
746
 
            try:
747
 
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
748
 
            except OSError as error:
749
 
                if error.errno == errno.ECHILD:
750
 
                    # This should never happen
751
 
                    logger.error("Child process vanished",
752
 
                                 exc_info=error)
753
 
                    return True
754
 
                raise
755
 
            if pid:
756
 
                gobject.source_remove(self.checker_callback_tag)
757
 
                self.checker_callback(pid, status, command)
 
971
            logger.info("Starting checker %r for %s", command,
 
972
                        self.name)
 
973
            # We don't need to redirect stdout and stderr, since
 
974
            # in normal mode, that is already done by daemon(),
 
975
            # and in debug mode we don't want to.  (Stdin is
 
976
            # always replaced by /dev/null.)
 
977
            # The exception is when not debugging but nevertheless
 
978
            # running in the foreground; use the previously
 
979
            # created wnull.
 
980
            popen_args = { "close_fds": True,
 
981
                           "shell": True,
 
982
                           "cwd": "/" }
 
983
            if (not self.server_settings["debug"]
 
984
                and self.server_settings["foreground"]):
 
985
                popen_args.update({"stdout": wnull,
 
986
                                   "stderr": wnull })
 
987
            pipe = multiprocessing.Pipe(duplex = False)
 
988
            self.checker = multiprocessing.Process(
 
989
                target = call_pipe,
 
990
                args = (pipe[1], subprocess.call, command),
 
991
                kwargs = popen_args)
 
992
            self.checker.start()
 
993
            self.checker_callback_tag = gobject.io_add_watch(
 
994
                pipe[0].fileno(), gobject.IO_IN,
 
995
                self.checker_callback, pipe[0], command)
758
996
        # Re-run this periodically if run by gobject.timeout_add
759
997
        return True
760
998
    
766
1004
        if getattr(self, "checker", None) is None:
767
1005
            return
768
1006
        logger.debug("Stopping checker for %(name)s", vars(self))
769
 
        try:
770
 
            self.checker.terminate()
771
 
            #time.sleep(0.5)
772
 
            #if self.checker.poll() is None:
773
 
            #    self.checker.kill()
774
 
        except OSError as error:
775
 
            if error.errno != errno.ESRCH: # No such process
776
 
                raise
 
1007
        self.checker.terminate()
777
1008
        self.checker = None
778
1009
 
779
1010
 
843
1074
                           access="r")
844
1075
    def Property_dbus_property(self):
845
1076
        return dbus.Boolean(False)
 
1077
    
 
1078
    See also the DBusObjectWithAnnotations class.
846
1079
    """
847
1080
    
848
1081
    def decorator(func):
870
1103
    pass
871
1104
 
872
1105
 
873
 
class DBusObjectWithProperties(dbus.service.Object):
874
 
    """A D-Bus object with properties.
 
1106
class DBusObjectWithAnnotations(dbus.service.Object):
 
1107
    """A D-Bus object with annotations.
875
1108
    
876
 
    Classes inheriting from this can use the dbus_service_property
877
 
    decorator to expose methods as D-Bus properties.  It exposes the
878
 
    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.
879
1111
    """
880
1112
    
881
1113
    @staticmethod
897
1129
                for name, athing in
898
1130
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
899
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
    
900
1203
    def _get_dbus_property(self, interface_name, property_name):
901
1204
        """Returns a bound method if one exists which is a D-Bus
902
1205
        property with the specified name and interface.
912
1215
        raise DBusPropertyNotFound("{}:{}.{}".format(
913
1216
            self.dbus_object_path, interface_name, property_name))
914
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
    
915
1227
    @dbus.service.method(dbus.PROPERTIES_IFACE,
916
1228
                         in_signature="ss",
917
1229
                         out_signature="v")
987
1299
        
988
1300
        Inserts property tags and interface annotation tags.
989
1301
        """
990
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
991
 
                                                   connection)
 
1302
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
 
1303
                                                         object_path,
 
1304
                                                         connection)
992
1305
        try:
993
1306
            document = xml.dom.minidom.parseString(xmlstring)
994
1307
            
1007
1320
                            if prop._dbus_interface
1008
1321
                            == if_tag.getAttribute("name")):
1009
1322
                    if_tag.appendChild(tag)
1010
 
                # Add annotation tags
1011
 
                for typ in ("method", "signal", "property"):
1012
 
                    for tag in if_tag.getElementsByTagName(typ):
1013
 
                        annots = dict()
1014
 
                        for name, prop in (self.
1015
 
                                           _get_all_dbus_things(typ)):
1016
 
                            if (name == tag.getAttribute("name")
1017
 
                                and prop._dbus_interface
1018
 
                                == if_tag.getAttribute("name")):
1019
 
                                annots.update(getattr(
1020
 
                                    prop, "_dbus_annotations", {}))
1021
 
                        for name, value in annots.items():
1022
 
                            ann_tag = document.createElement(
1023
 
                                "annotation")
1024
 
                            ann_tag.setAttribute("name", name)
1025
 
                            ann_tag.setAttribute("value", value)
1026
 
                            tag.appendChild(ann_tag)
1027
 
                # Add interface annotation tags
1028
 
                for annotation, value in dict(
1029
 
                    itertools.chain.from_iterable(
1030
 
                        annotations().items()
1031
 
                        for name, annotations
1032
 
                        in self._get_all_dbus_things("interface")
1033
 
                        if name == if_tag.getAttribute("name")
1034
 
                        )).items():
1035
 
                    ann_tag = document.createElement("annotation")
1036
 
                    ann_tag.setAttribute("name", annotation)
1037
 
                    ann_tag.setAttribute("value", value)
1038
 
                    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)
1039
1339
                # Add the names to the return values for the
1040
1340
                # "org.freedesktop.DBus.Properties" methods
1041
1341
                if (if_tag.getAttribute("name")
1059
1359
                         exc_info=error)
1060
1360
        return xmlstring
1061
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
1062
1430
 
1063
1431
def datetime_to_dbus(dt, variant_level=0):
1064
1432
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1111
1479
                interface_names.add(alt_interface)
1112
1480
                # Is this a D-Bus signal?
1113
1481
                if getattr(attribute, "_dbus_is_signal", False):
1114
 
                    # Extract the original non-method undecorated
1115
 
                    # function by black magic
1116
 
                    nonmethod_func = (dict(
1117
 
                        zip(attribute.func_code.co_freevars,
1118
 
                            attribute.__closure__))
1119
 
                                      ["func"].cell_contents)
 
1482
                    if sys.version_info.major == 2:
 
1483
                        # Extract the original non-method undecorated
 
1484
                        # function by black magic
 
1485
                        nonmethod_func = (dict(
 
1486
                            zip(attribute.func_code.co_freevars,
 
1487
                                attribute.__closure__))
 
1488
                                          ["func"].cell_contents)
 
1489
                    else:
 
1490
                        nonmethod_func = attribute
1120
1491
                    # Create a new, but exactly alike, function
1121
1492
                    # object, and decorate it to be a new D-Bus signal
1122
1493
                    # with the alternate D-Bus interface name
 
1494
                    if sys.version_info.major == 2:
 
1495
                        new_function = types.FunctionType(
 
1496
                            nonmethod_func.func_code,
 
1497
                            nonmethod_func.func_globals,
 
1498
                            nonmethod_func.func_name,
 
1499
                            nonmethod_func.func_defaults,
 
1500
                            nonmethod_func.func_closure)
 
1501
                    else:
 
1502
                        new_function = types.FunctionType(
 
1503
                            nonmethod_func.__code__,
 
1504
                            nonmethod_func.__globals__,
 
1505
                            nonmethod_func.__name__,
 
1506
                            nonmethod_func.__defaults__,
 
1507
                            nonmethod_func.__closure__)
1123
1508
                    new_function = (dbus.service.signal(
1124
 
                        alt_interface, attribute._dbus_signature)
1125
 
                                    (types.FunctionType(
1126
 
                                        nonmethod_func.func_code,
1127
 
                                        nonmethod_func.func_globals,
1128
 
                                        nonmethod_func.func_name,
1129
 
                                        nonmethod_func.func_defaults,
1130
 
                                        nonmethod_func.func_closure)))
 
1509
                        alt_interface,
 
1510
                        attribute._dbus_signature)(new_function))
1131
1511
                    # Copy annotations, if any
1132
1512
                    try:
1133
1513
                        new_function._dbus_annotations = dict(
1143
1523
                        func1 and func2 to the "call_both" function
1144
1524
                        outside of its arguments"""
1145
1525
                        
 
1526
                        @functools.wraps(func2)
1146
1527
                        def call_both(*args, **kwargs):
1147
1528
                            """This function will emit two D-Bus
1148
1529
                            signals by calling func1 and func2"""
1149
1530
                            func1(*args, **kwargs)
1150
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)
1151
1536
                        
1152
1537
                        return call_both
1153
1538
                    # Create the "call_both" function and add it to
1356
1741
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1357
1742
        Client.__del__(self, *args, **kwargs)
1358
1743
    
1359
 
    def checker_callback(self, pid, condition, command,
1360
 
                         *args, **kwargs):
1361
 
        self.checker_callback_tag = None
1362
 
        self.checker = None
1363
 
        if os.WIFEXITED(condition):
1364
 
            exitstatus = os.WEXITSTATUS(condition)
 
1744
    def checker_callback(self, source, condition,
 
1745
                         connection, command, *args, **kwargs):
 
1746
        ret = Client.checker_callback(self, source, condition,
 
1747
                                      connection, command, *args,
 
1748
                                      **kwargs)
 
1749
        exitstatus = self.last_checker_status
 
1750
        if exitstatus >= 0:
1365
1751
            # Emit D-Bus signal
1366
1752
            self.CheckerCompleted(dbus.Int16(exitstatus),
1367
 
                                  dbus.Int64(condition),
 
1753
                                  # This is specific to GNU libC
 
1754
                                  dbus.Int64(exitstatus << 8),
1368
1755
                                  dbus.String(command))
1369
1756
        else:
1370
1757
            # Emit D-Bus signal
1371
1758
            self.CheckerCompleted(dbus.Int16(-1),
1372
 
                                  dbus.Int64(condition),
 
1759
                                  dbus.Int64(
 
1760
                                      # This is specific to GNU libC
 
1761
                                      (exitstatus << 8)
 
1762
                                      | self.last_checker_signal),
1373
1763
                                  dbus.String(command))
1374
 
        
1375
 
        return Client.checker_callback(self, pid, condition, command,
1376
 
                                       *args, **kwargs)
 
1764
        return ret
1377
1765
    
1378
1766
    def start_checker(self, *args, **kwargs):
1379
1767
        old_checker_pid = getattr(self.checker, "pid", None)
1454
1842
        self.checked_ok()
1455
1843
    
1456
1844
    # Enable - method
 
1845
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1457
1846
    @dbus.service.method(_interface)
1458
1847
    def Enable(self):
1459
1848
        "D-Bus method"
1460
1849
        self.enable()
1461
1850
    
1462
1851
    # StartChecker - method
 
1852
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1463
1853
    @dbus.service.method(_interface)
1464
1854
    def StartChecker(self):
1465
1855
        "D-Bus method"
1466
1856
        self.start_checker()
1467
1857
    
1468
1858
    # Disable - method
 
1859
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1469
1860
    @dbus.service.method(_interface)
1470
1861
    def Disable(self):
1471
1862
        "D-Bus method"
1472
1863
        self.disable()
1473
1864
    
1474
1865
    # StopChecker - method
 
1866
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1475
1867
    @dbus.service.method(_interface)
1476
1868
    def StopChecker(self):
1477
1869
        self.stop_checker()
1513
1905
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1514
1906
    
1515
1907
    # Name - property
 
1908
    @dbus_annotations(
 
1909
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1516
1910
    @dbus_service_property(_interface, signature="s", access="read")
1517
1911
    def Name_dbus_property(self):
1518
1912
        return dbus.String(self.name)
1519
1913
    
1520
1914
    # Fingerprint - property
 
1915
    @dbus_annotations(
 
1916
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1521
1917
    @dbus_service_property(_interface, signature="s", access="read")
1522
1918
    def Fingerprint_dbus_property(self):
1523
1919
        return dbus.String(self.fingerprint)
1532
1928
        self.host = str(value)
1533
1929
    
1534
1930
    # Created - property
 
1931
    @dbus_annotations(
 
1932
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1535
1933
    @dbus_service_property(_interface, signature="s", access="read")
1536
1934
    def Created_dbus_property(self):
1537
1935
        return datetime_to_dbus(self.created)
1652
2050
            self.stop_checker()
1653
2051
    
1654
2052
    # ObjectPath - property
 
2053
    @dbus_annotations(
 
2054
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
 
2055
         "org.freedesktop.DBus.Deprecated": "true"})
1655
2056
    @dbus_service_property(_interface, signature="o", access="read")
1656
2057
    def ObjectPath_dbus_property(self):
1657
2058
        return self.dbus_object_path # is already a dbus.ObjectPath
1658
2059
    
1659
2060
    # Secret = property
 
2061
    @dbus_annotations(
 
2062
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2063
         "invalidates"})
1660
2064
    @dbus_service_property(_interface,
1661
2065
                           signature="ay",
1662
2066
                           access="write",
1708
2112
            logger.debug("Pipe FD: %d",
1709
2113
                         self.server.child_pipe.fileno())
1710
2114
            
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.
 
2115
            session = gnutls.ClientSession(self.request)
1718
2116
            
1719
2117
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1720
2118
            #                      "+AES-256-CBC", "+SHA1",
1724
2122
            priority = self.server.gnutls_priority
1725
2123
            if priority is None:
1726
2124
                priority = "NORMAL"
1727
 
            gnutls.library.functions.gnutls_priority_set_direct(
1728
 
                session._c_object, priority, None)
 
2125
            gnutls.priority_set_direct(session._c_object, priority,
 
2126
                                       None)
1729
2127
            
1730
2128
            # Start communication using the Mandos protocol
1731
2129
            # Get protocol number
1741
2139
            # Start GnuTLS connection
1742
2140
            try:
1743
2141
                session.handshake()
1744
 
            except gnutls.errors.GNUTLSError as error:
 
2142
            except gnutls.Error as error:
1745
2143
                logger.warning("Handshake failed: %s", error)
1746
2144
                # Do not run session.bye() here: the session is not
1747
2145
                # established.  Just abandon the request.
1753
2151
                try:
1754
2152
                    fpr = self.fingerprint(
1755
2153
                        self.peer_certificate(session))
1756
 
                except (TypeError,
1757
 
                        gnutls.errors.GNUTLSError) as error:
 
2154
                except (TypeError, gnutls.Error) as error:
1758
2155
                    logger.warning("Bad certificate: %s", error)
1759
2156
                    return
1760
2157
                logger.debug("Fingerprint: %s", fpr)
1822
2219
                while sent_size < len(client.secret):
1823
2220
                    try:
1824
2221
                        sent = session.send(client.secret[sent_size:])
1825
 
                    except gnutls.errors.GNUTLSError as error:
 
2222
                    except gnutls.Error as error:
1826
2223
                        logger.warning("gnutls send failed",
1827
2224
                                       exc_info=error)
1828
2225
                        return
1843
2240
                    client.approvals_pending -= 1
1844
2241
                try:
1845
2242
                    session.bye()
1846
 
                except gnutls.errors.GNUTLSError as error:
 
2243
                except gnutls.Error as error:
1847
2244
                    logger.warning("GnuTLS bye failed",
1848
2245
                                   exc_info=error)
1849
2246
    
1851
2248
    def peer_certificate(session):
1852
2249
        "Return the peer's OpenPGP certificate as a bytestring"
1853
2250
        # If not an OpenPGP certificate...
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
 
2251
        if (gnutls.certificate_type_get(session._c_object)
 
2252
            != gnutls.CRT_OPENPGP):
 
2253
            # ...return invalid data
 
2254
            return b""
1859
2255
        list_size = ctypes.c_uint(1)
1860
 
        cert_list = (gnutls.library.functions
1861
 
                     .gnutls_certificate_get_peers
 
2256
        cert_list = (gnutls.certificate_get_peers
1862
2257
                     (session._c_object, ctypes.byref(list_size)))
1863
2258
        if not bool(cert_list) and list_size.value != 0:
1864
 
            raise gnutls.errors.GNUTLSError("error getting peer"
1865
 
                                            " certificate")
 
2259
            raise gnutls.Error("error getting peer certificate")
1866
2260
        if list_size.value == 0:
1867
2261
            return None
1868
2262
        cert = cert_list[0]
1872
2266
    def fingerprint(openpgp):
1873
2267
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1874
2268
        # New GnuTLS "datum" with the OpenPGP public key
1875
 
        datum = gnutls.library.types.gnutls_datum_t(
 
2269
        datum = gnutls.datum_t(
1876
2270
            ctypes.cast(ctypes.c_char_p(openpgp),
1877
2271
                        ctypes.POINTER(ctypes.c_ubyte)),
1878
2272
            ctypes.c_uint(len(openpgp)))
1879
2273
        # New empty GnuTLS certificate
1880
 
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1881
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1882
 
            ctypes.byref(crt))
 
2274
        crt = gnutls.openpgp_crt_t()
 
2275
        gnutls.openpgp_crt_init(ctypes.byref(crt))
1883
2276
        # Import the OpenPGP public key into the certificate
1884
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1885
 
            crt, ctypes.byref(datum),
1886
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
2277
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
 
2278
                                  gnutls.OPENPGP_FMT_RAW)
1887
2279
        # Verify the self signature in the key
1888
2280
        crtverify = ctypes.c_uint()
1889
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1890
 
            crt, 0, ctypes.byref(crtverify))
 
2281
        gnutls.openpgp_crt_verify_self(crt, 0,
 
2282
                                       ctypes.byref(crtverify))
1891
2283
        if crtverify.value != 0:
1892
 
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1893
 
            raise gnutls.errors.CertificateSecurityError(
1894
 
                "Verify failed")
 
2284
            gnutls.openpgp_crt_deinit(crt)
 
2285
            raise gnutls.CertificateSecurityError("Verify failed")
1895
2286
        # New buffer for the fingerprint
1896
2287
        buf = ctypes.create_string_buffer(20)
1897
2288
        buf_len = ctypes.c_size_t()
1898
2289
        # Get the fingerprint from the certificate into the buffer
1899
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1900
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
2290
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
2291
                                           ctypes.byref(buf_len))
1901
2292
        # Deinit the certificate
1902
 
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
2293
        gnutls.openpgp_crt_deinit(crt)
1903
2294
        # Convert the buffer to a Python bytestring
1904
2295
        fpr = ctypes.string_at(buf, buf_len.value)
1905
2296
        # Convert the bytestring to hexadecimal notation
2141
2532
        
2142
2533
        if command == 'getattr':
2143
2534
            attrname = request[1]
2144
 
            if callable(client_object.__getattribute__(attrname)):
 
2535
            if isinstance(client_object.__getattribute__(attrname),
 
2536
                          collections.Callable):
2145
2537
                parent_pipe.send(('function', ))
2146
2538
            else:
2147
2539
                parent_pipe.send((
2182
2574
    # avoid excessive use of external libraries.
2183
2575
    
2184
2576
    # New type for defining tokens, syntax, and semantics all-in-one
2185
 
    Token = collections.namedtuple("Token",
2186
 
                                   ("regexp", # To match token; if
2187
 
                                              # "value" is not None,
2188
 
                                              # must have a "group"
2189
 
                                              # containing digits
2190
 
                                    "value",  # datetime.timedelta or
2191
 
                                              # None
2192
 
                                    "followers")) # Tokens valid after
2193
 
                                                  # this token
2194
2577
    Token = collections.namedtuple("Token", (
2195
2578
        "regexp",  # To match token; if "value" is not None, must have
2196
2579
                   # a "group" containing digits
2231
2614
    # Define starting values
2232
2615
    value = datetime.timedelta() # Value so far
2233
2616
    found_token = None
2234
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2617
    followers = frozenset((token_duration, )) # Following valid tokens
2235
2618
    s = duration                # String left to parse
2236
2619
    # Loop until end token is found
2237
2620
    while found_token is not token_end:
2394
2777
                        "debug": "False",
2395
2778
                        "priority":
2396
2779
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2397
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2780
                        ":+SIGN-DSA-SHA256",
2398
2781
                        "servicename": "Mandos",
2399
2782
                        "use_dbus": "True",
2400
2783
                        "use_ipv6": "True",
2539
2922
        
2540
2923
        # "Use a log level over 10 to enable all debugging options."
2541
2924
        # - GnuTLS manual
2542
 
        gnutls.library.functions.gnutls_global_set_log_level(11)
 
2925
        gnutls.global_set_log_level(11)
2543
2926
        
2544
 
        @gnutls.library.types.gnutls_log_func
 
2927
        @gnutls.log_func
2545
2928
        def debug_gnutls(level, string):
2546
2929
            logger.debug("GnuTLS: %s", string[:-1])
2547
2930
        
2548
 
        gnutls.library.functions.gnutls_global_set_log_function(
2549
 
            debug_gnutls)
 
2931
        gnutls.global_set_log_function(debug_gnutls)
2550
2932
        
2551
2933
        # Redirect stdin so all checkers get /dev/null
2552
2934
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2656
3038
                    pass
2657
3039
            
2658
3040
            # Clients who has passed its expire date can still be
2659
 
            # enabled if its last checker was successful.  Clients
 
3041
            # enabled if its last checker was successful.  A Client
2660
3042
            # whose checker succeeded before we stored its state is
2661
3043
            # assumed to have successfully run all checkers during
2662
3044
            # downtime.
2731
3113
        
2732
3114
        @alternate_dbus_interfaces(
2733
3115
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
2734
 
        class MandosDBusService(DBusObjectWithProperties):
 
3116
        class MandosDBusService(DBusObjectWithObjectManager):
2735
3117
            """A D-Bus proxy object"""
2736
3118
            
2737
3119
            def __init__(self):
2739
3121
            
2740
3122
            _interface = "se.recompile.Mandos"
2741
3123
            
2742
 
            @dbus_interface_annotations(_interface)
2743
 
            def _foo(self):
2744
 
                return {
2745
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2746
 
                    "false" }
2747
 
            
2748
3124
            @dbus.service.signal(_interface, signature="o")
2749
3125
            def ClientAdded(self, objpath):
2750
3126
                "D-Bus signal"
2755
3131
                "D-Bus signal"
2756
3132
                pass
2757
3133
            
 
3134
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3135
                               "true"})
2758
3136
            @dbus.service.signal(_interface, signature="os")
2759
3137
            def ClientRemoved(self, objpath, name):
2760
3138
                "D-Bus signal"
2761
3139
                pass
2762
3140
            
 
3141
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3142
                               "true"})
2763
3143
            @dbus.service.method(_interface, out_signature="ao")
2764
3144
            def GetAllClients(self):
2765
3145
                "D-Bus method"
2766
3146
                return dbus.Array(c.dbus_object_path for c in
2767
3147
                                  tcp_server.clients.itervalues())
2768
3148
            
 
3149
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
 
3150
                               "true"})
2769
3151
            @dbus.service.method(_interface,
2770
3152
                                 out_signature="a{oa{sv}}")
2771
3153
            def GetAllClientsWithProperties(self):
2772
3154
                "D-Bus method"
2773
3155
                return dbus.Dictionary(
2774
 
                    { c.dbus_object_path: c.GetAll("")
 
3156
                    { c.dbus_object_path: c.GetAll(
 
3157
                        "se.recompile.Mandos.Client")
2775
3158
                      for c in tcp_server.clients.itervalues() },
2776
3159
                    signature="oa{sv}")
2777
3160
            
2782
3165
                    if c.dbus_object_path == object_path:
2783
3166
                        del tcp_server.clients[c.name]
2784
3167
                        c.remove_from_connection()
2785
 
                        # Don't signal anything except ClientRemoved
 
3168
                        # Don't signal the disabling
2786
3169
                        c.disable(quiet=True)
2787
 
                        # Emit D-Bus signal
2788
 
                        self.ClientRemoved(object_path, c.name)
 
3170
                        # Emit D-Bus signal for removal
 
3171
                        self.client_removed_signal(c)
2789
3172
                        return
2790
3173
                raise KeyError(object_path)
2791
3174
            
2792
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)
2793
3212
        
2794
3213
        mandos_dbus_service = MandosDBusService()
2795
3214
    
2860
3279
            name, client = tcp_server.clients.popitem()
2861
3280
            if use_dbus:
2862
3281
                client.remove_from_connection()
2863
 
            # Don't signal anything except ClientRemoved
 
3282
            # Don't signal the disabling
2864
3283
            client.disable(quiet=True)
 
3284
            # Emit D-Bus signal for removal
2865
3285
            if use_dbus:
2866
 
                # Emit D-Bus signal
2867
 
                mandos_dbus_service.ClientRemoved(
2868
 
                    client.dbus_object_path, client.name)
 
3286
                mandos_dbus_service.client_removed_signal(client)
2869
3287
        client_settings.clear()
2870
3288
    
2871
3289
    atexit.register(cleanup)
2872
3290
    
2873
3291
    for client in tcp_server.clients.itervalues():
2874
3292
        if use_dbus:
2875
 
            # Emit D-Bus signal
2876
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
3293
            # Emit D-Bus signal for adding
 
3294
            mandos_dbus_service.client_added_signal(client)
2877
3295
        # Need to initiate checking of clients
2878
3296
        if client.enabled:
2879
3297
            client.init_checker()